@author jackzhenguo
@desc
@date 2019/3/6
检查对象是否可被调用
In [1]: callable(str)
Out[1]: True
In [2]: callable(int)
Out[2]: True
In [18]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
...
In [19]: xiaoming = Student('001','xiaoming')
In [20]: callable(xiaoming)
Out[20]: False
如果能调用xiaoming()
, 需要重写Student
类的__call__
方法:
In [1]: class Student():
...: def __init__(self,id,name):
...: self.id = id
...: self.name = name
...: def __repr__(self):
...: return 'id = '+self.id +', name = '+self.name
...: def __call__(self):
...: print('I can be called')
...: print(f'my name is {self.name}')
...:
In [2]: t = Student('001','xiaoming')
In [3]: t()
I can be called
my name is xiaoming