[英]decorate __call__ with @staticmethod
Why can't I make a class' __call__ method static using the @staticmethod decorator? 为什么我不能使用@staticmethod装饰器使类'__call__方法静态?
class Foo(object):
@staticmethod
def bar():
return 'bar'
@staticmethod
def __call__():
return '__call__'
print Foo.bar()
print Foo()
outputs 输出
bar
<__main__.Foo object at 0x7fabf93c89d0>
but I would expect it to output 但我希望它输出
bar
__call__
You need to override __call__
on the metaclass. 您需要覆盖元类上的
__call__
。 The special methods defined in a class are for its instances, to change a class's special methods you need to change them in its class, ie metaclass. 类中定义的特殊方法是为其实例更改类中需要在类中更改它们的特殊方法,即元类。 (When you call
Foo()
usually the order is: Meta.__call__()
--> Foo.__new__()
--> Foo.__init__()
, only if they return normally) (当你调用
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__
As you're trying to modify class instantiation, another way will be to override __new__
on the class itself and return __call__
from it(when __new__
returns something other than an instance the __init__
method is never called): 正如你想修改类实例化,另一种方式将覆盖
__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.