我想表示可以是 None、列表或字典的对象,因此我为此创建一个类,例如
class C(object):
def __init__(self,c):
self.content = c
现在我可以重写什么__method__
来检查C对象o是否为None或空,以便我可以做一些事情,例如if o:做某事,例如,
c1 = C(None)
c2 = C([])
c3 = C([1])
'1'if c1 else '0'
'1' #I want this to be '0'
sage: '1'if c2 else '0'
'1' # I want this to be '0'
sage: '1'if c3 else '0'
最佳答案
尝试定义__nonzero__
。
class C(object):
def __init__(self,c):
self.content = c
def __nonzero__(self):
return bool(self.content)
c1 = C(None)
c2 = C([])
c3 = C([1])
print 1 if c1 else 0 #result: 0
print 1 if c2 else 0 #result: 0
print 1 if c3 else 0 #result: 1
关于python - 重写类方法以检查是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30485152/