我来自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()
输出:
确定
答案 0 :(得分:1)
来自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"