Python decorator as a staticmethod

前端 未结 4 1725
天涯浪人
天涯浪人 2020-11-28 10:42

I\'m trying to write a python class which uses a decorator function that needs information of the instance state. This is working as intended, but if I explicitly make the d

4条回答
  •  鱼传尺愫
    2020-11-28 10:46

    This is not how staticmethod is supposed to be used. staticmethod objects are descriptors that return the wrapped object, so they only work when accessed as classname.staticmethodname. Example

    class A(object):
        @staticmethod
        def f():
            pass
    print A.f
    print A.__dict__["f"]
    

    prints

    
    
    

    Inside the scope of A, you would always get the latter object, which is not callable.

    I'd strongly recommend to move the decorator to the module scope -- it does not seem to belong inside the class. If you want to keep it inside the class, don't make it a staticmethod, but rather simply del it at the end of the class body -- it's not meant to be used from outside the class in this case.

提交回复
热议问题