阅读量

原创教程,严禁转载。引用本文,请署名 Python中文网, http://www.zglg.work


@author jackzhenguo
@desc 
@date 2019/3/6

33 对象是否可调用

检查对象是否可被调用

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

上一个例子 下一个例子