Beautify __call__ with @staticmethod

Why can't I make a static method of the __call__ class using the @staticmethod decorator?

class Foo(object): @staticmethod def bar(): return 'bar' @staticmethod def __call__(): return '__call__' print Foo.bar() print Foo() 

exits

 bar <__main__.Foo object at 0x7fabf93c89d0> 

but I expect him to output

 bar __call__ 
+7
python decorator python-decorators static-methods
source share
1 answer

You need to override __call__ in the metaclass. The special methods defined in the class are intended for its instances in order to change the special methods of the class needed to change them in its class, that is, in the metaclass. (When you call Foo() , usually the order is: Meta.__call__()Foo.__new__()Foo.__init__() only if they return normally)

 class Meta(type): @staticmethod def __call__(): return '__call__' class Foo(object): __metaclass__ = Meta @staticmethod def bar(): return 'bar' print Foo() #__call__ 

As you try to modify an instance of a class, another way is to override __new__ in the class itself and return __call__ from it (when __new__ returns something other than the instance, the __init__ method is never called):

 class Foo(object): def __new__(*args): #ignore the args return '__call__' @staticmethod def bar(): return 'bar' print Foo() #__call__ 
+12
source share

All Articles