Python 为什么我不能访问成员函数中的其他静态成员函数? 我来自C++,我想访问一个成员函数中的另一个静态成员函数。
S1: 输出: 错误,未定义hello S2: 输出: 好的来自文档: 静态方法不接收隐式第一个参数 它既可以在类(如C.f)上调用,也可以在实例(如C.f)上调用 您仍然需要自引用对象。否则,解释器将查找名为hello的顶级函数 希望这个例子解释得更好Python 为什么我不能访问成员函数中的其他静态成员函数? 我来自C++,我想访问一个成员函数中的另一个静态成员函数。,python,Python,S1: 输出: 错误,未定义hello S2: 输出: 好的来自文档: 静态方法不接收隐式第一个参数 它既可以在类(如C.f)上调用,也可以在实例(如C.f)上调用 您仍然需要自引用对象。否则,解释器将查找名为hello的顶级函数 希望这个例子解释得更好 def hello(): print("this is not the static method you are loking for") class Test: @staticmethod def hello(
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"
实际上,它只在顶级名称空间中查找hello。但它在课堂上是不会向上看的。为什么会发生这种情况解释器需要知道在哪里查找才能调用您的函数。staticmethod装饰器绑定类命名空间中的函数。因此,您需要引用类或对象。@LFBuildAMountain这是Python中的一个一般原则,并不特定于静态方法。与java或C++不同,您需要对所有方法和属性都明确地引用“自我”或另一个实例或类。
def hello():
print("hello outside")
def hey():
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"