跳转至

🔥AI副业赚钱星球

点击下面图片查看

郭震AI

33

编辑日期: 2024-11-28 文章阅读:

@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

上一个例子 下一个例子

京ICP备20031037号-1