[英]Python: decorate __call__ and ordinary function with the same decorator?
[英]decorate __call__ with @staticmethod
为什么我不能使用@staticmethod装饰器使类'__call__方法静态?
class Foo(object):
@staticmethod
def bar():
return 'bar'
@staticmethod
def __call__():
return '__call__'
print Foo.bar()
print Foo()
输出
bar
<__main__.Foo object at 0x7fabf93c89d0>
但我希望它输出
bar
__call__
您需要覆盖元类上的__call__
。 类中定义的特殊方法是为其实例更改类中需要在类中更改它们的特殊方法,即元类。 (当你调用Foo()
通常的顺序是: Meta.__call__()
- > Foo.__new__()
- > Foo.__init__()
,只有当它们正常返回时)
class Meta(type):
@staticmethod
def __call__():
return '__call__'
class Foo(object):
__metaclass__ = Meta
@staticmethod
def bar():
return 'bar'
print Foo()
#__call__
正如你想修改类实例化,另一种方式将覆盖__new__
类本身并返回__call__
从它(当__new__
返回以外的东西不是一个实例的__init__
方法不会被调用):
class Foo(object):
def __new__(*args):
#ignore the args
return '__call__'
@staticmethod
def bar():
return 'bar'
print Foo()
#__call__
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.