Skip to content

Latest commit

 

History

History
54 lines (43 loc) · 1.23 KB

33.md

File metadata and controls

54 lines (43 loc) · 1.23 KB
@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
[上一个例子](32.md) [下一个例子](34.md)