Python: possible to call static method from within class without qualifying the name

前端 未结 4 1240
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 11:07

This is annoying:

class MyClass:
    @staticmethod
    def foo():
        print \"hi\"

    @staticmethod
    def bar():
        MyClass.foo()
4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-01 11:48

    You can do something hacky by making a module level function foo and then adding it to the class namespace with staticmethod:

    def foo():
        print "hi"
    
    class MyClass(object):
        foo = staticmethod(foo)
    
        @classmethod
        def bar(cls):
            return cls.foo()
    
        def baz(self):
            return foo()
    
    
    c = MyClass()
    c.bar()
    c.baz()
    
    MyClass.bar()
    MyClass.foo()
    

提交回复
热议问题