覆盖类方法以检查空白

时间:2015-05-27 14:15:39

标签: python

我想表示可以是None,list或dict的对象,所以我为此创建了一个类,例如

class C(object):
    def __init__(self,c):
         self.content = c

现在可以覆盖__method__以检查C对象是否为None或为空,以便我可以执行某些操作,例如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'

2 个答案:

答案 0 :(得分:2)

尝试定义__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

答案 1 :(得分:1)

在Python 3中:

Do

打印:

class C(object):
    def __init__(self,c):
         self.content = c
    def __bool__(self):
        return bool(self.content)
c1 = C(None)
c1 = C(None)
c2 = C([])
c3 = C([1])
print('1'if c1 else '0')
print('1'if c2 else '0')
print('1'if c3 else '0')

Python 2和3

0  
0
1