2015-05-27 99 views
2

我要代表的對象,可以是無,列表或字典,所以我創建了這個類,例如,覆蓋類的方法來檢查emptyness

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

現在什麼__method__可我重寫以檢查對象C o是無或空的,所以我可以做一些事情,例如如果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

嘗試定義__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 
+0

或者Python中的'__bool__' 3+ –

1

在Python 3:

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') 

打印:

0 
0 
1 

Python 2和3

class C(object): 
    def __init__(self,c): 
     self.content = c 
    def __bool__(self): 
     return bool(self.content) 
    __nonzero__ = __bool__ 
+0

謝謝,我用Python 2,但我喜歡你的建議,使代碼兼容與兩個版本 –