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

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

This is annoying:

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

    @staticmethod
    def bar():
        MyClass.foo()
4条回答
  •  抹茶落季
    2021-01-01 12:08

    There is no way to use foo and get what you want. There is no implicit class scope, so foo is either a local or a global, neither of which you want.

    You might find classmethods more useful:

    class MyClass:
        @classmethod
        def foo(cls):
            print "hi"
    
        @classmethod
        def bar(cls):
            cls.foo()
    

    This way, at least you don't have to repeat the name of the class.

提交回复
热议问题