我理解 staticmethod 应该始终通过它们所属的类名来引用。但我发现它们也可以通过关键字 self 访问。
这有点令人困惑,我没有看到解释器抛出错误。
import unittest
class TestA(unittest.TestCase):
@staticmethod
def fun1():
return True
@staticmethod
def fun2():
return False
def test_one(self):
assert TestA.fun1() == True
def test_two(self):
assert self.fun2() == False
if __name__ == '__main__':
unittest.main()
访问静态方法的正确方法是什么。就像上面的 TestA.fun1
这对我来说很清楚,或者 self.fun2
这有点令人担忧,因为没有实例发送到 fun2。
最佳答案
任何一种方式都可以接受,如 the documentation 中所述。 :
It can be called either on the class (such as
C.f()
) or on an instance (such asC().f()
). The instance is ignored except for its class.
从某种意义上说,静态方法的要点是允许您调用该方法,而不必担心是在实例上还是在类上调用它。
关于python - 在 Python 中访问类中静态方法的惯用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24334739/