用@staticmethod装饰__call__

时间:2014-11-07 03:32:11

标签: python decorator static-methods python-decorators

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

1 个答案:

答案 0 :(得分:15)

您需要覆盖元类上的__call__。类中定义的特殊方法是为其实例更改类中需要在类中更改它们的特殊方法,即元类。 (当您致电Foo()时,订单通常是:Meta.__call__() - &gt; Foo.__new__() - &gt; 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__