python 类 __call__
Posted minger_lcm
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 类 __call__相关的知识,希望对你有一定的参考价值。
__call__ 对象后面加括号,触发执行。
即:对象() 或者 类()()
class dog(object): def __init__(self,name): self.name = name def eat(self): print("%s is eating %s" % (self.name,‘ss‘)) def talk(self): print("%s is taking" % self.name) def __call__(self, *args, **kwargs): print("you are ok?", args, kwargs) d = dog("jianlin") d() d(1,2,3,name="mike") ‘‘‘ you are ok? () {} you are ok? (1, 2, 3) {‘name‘: ‘mike‘} ‘‘‘
另外一种实现
class dog(object): def __init__(self,name): self.name = name def eat(self): print("%s is eating %s" % (self.name,‘ss‘)) def talk(self): print("%s is taking" % self.name) def __call__(self, *args, **kwargs): print("you are ok?", args, kwargs) dog("jianlin")() # you are ok? () {}
以上是关于python 类 __call__的主要内容,如果未能解决你的问题,请参考以下文章
AttributeError : 类实例没有 __call__ 方法