1、判断对象是否可被调用
能被调用的对象就是一个callable对象,比如函数str, int 等都是可被调用的
callable(int)
callable(str)
out: True
2、类中实例的调用:
(1)如果直接调用类中的实例,是不可行的:
class Student():
def __init__(self,id,name):
self.id = id
self.name = name
def __repr__(self):
return 'id = '+self.id+', name'+self.name
han = Student(id="001", name="xiaoming")
callable(han)
out: False
(2)如果想要能够被调用,需要重写Student类的call方法:
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 now")
print("my name is {}".format(self.name))
han = Student(id="001", name="xiaoming")
han()
callable(han)
out:
I can be called now
my name is xiaoming
True
总结:如果让类中实例可调用,需要加上def __call__(self)。
网友评论