__contains__():對類執行個體使用in ,not in操作時調用
class A(object):
def __init__(self,num):
self.num=num
def __contains__(self,item):
print('__contains__: %s is in ?' % item )
if item < self.num and item >= 0 :
return True
else :
return False
if __name__=='__main__':
if 3 in A(10):
print('True')
else:
print('False')
輸出:
__contains__: 3 is in ?
True
__call__():像函數一樣調用類執行個體時使用的方法
class Person(object):
def __init__(self,name,gender):
self.name=name
self.gender=gender
def __call__(self,friend):
print('My name is %s ...' % self.name)
print('My friends is %s ...' % friend)
p=Person('Bob','male')
p('Tim')
輸出:
My name is Bob ...
My friends is Tim ...
轉載于:https://www.cnblogs.com/Ting-light/p/9548090.html