Python: possible to call static method from within

2019-02-11 18:14发布

This is annoying:

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

    @staticmethod
    def bar():
        MyClass.foo()

Is there a way to make this work without naming MyClass in the call? i.e. so I can just say foo() on the last line?

3条回答
一纸荒年 Trace。
2楼-- · 2019-02-11 18:43

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.

查看更多
The star\"
3楼-- · 2019-02-11 18:48

Not possible. It is a question of language design. Compare that to C++, where both this (the same as Python self; in Python you have to write self.var, in C++ you may write just var, not this->var) and own class are used by default in member functions, and you will probably see that sometimes that's good and sometimes that's annoying. The only thing possible is to get used to that feature.

查看更多
唯我独甜
4楼-- · 2019-02-11 19:05

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()
查看更多
登录 后发表回答