python 定義class時的內置方法
__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 ...
python 定義class時的內置方法