为什么我无法访问成员函数中的其他静态成员函数?



我来自C++,我想在一个成员函数中访问另一个静态成员函数。

S1:

class Test:
    @staticmethod
    def hello():
        print("static method is on")
    def hey(self):
        hello()

输出:

错误,未定义 hello((

S2:

def hello():
    print("hello outside")
def hey():
    hello()

输出:

还行

来自 staticmethod文档:

静态方法不会接收隐式第一个参数。

它可以在类(如 C.f(((或实例(如 C((.f(((上调用。

您仍然需要自引用对象。否则,解释器将查找名为 hello 的顶级函数。

class Test:
    @staticmethod
    def hello():
        print("static method is on")
    def hey(self):
        self.hello()

t = Test()
t.hey()
out: "static method is on"
Test.hey()
out: "static method is on"

希望这个例子能更好地解释。

def hello():
    print("this is not the static method you are loking for")

class Test:
    @staticmethod
    def hello():
        print("static method is on")
    def hey(self):
        hello()

t = Test()
t.hey()
out: "this is not the static method you are loking for"

相关内容

最新更新