__call__, __str__


一个类实例也可以变成一个可调用对象,只需要实现一个特殊方法__call__()
class People:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return "his name is %s" % self.name

    def __call__(self, gender):
        print("he is a " + gender)


human1 = People("jack", 34)
print(human1)   # 当使用print输出对象的时候,只要自己定义了__str__(self)方法,那么就会打印从在这个方法中return的数据
human1("male")  # 可直接对实例进行调用,就像使用函数一样

输出

his name is jack
he is a male

 

 

 

 

参考:

https://www.runoob.com/note/41154

https://www.cnblogs.com/superxuezhazha/p/5793536.html

https://blog.csdn.net/Nekocharm/article/details/98326720

posted @ 2020-04-15 14:07  坚强的小蚂蚁  阅读(125)  评论(0编辑  收藏  举报