gpt4 book ai didi

python - 用@staticmethod 修饰 __call__

转载 作者:太空狗 更新时间:2023-10-29 18:01:30 28 4
gpt4 key购买 nike

为什么我不能使用 @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__

关于python - 用@staticmethod 修饰 __call__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26793600/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com