【发布时间】:2021-08-10 05:44:31
【问题描述】:
我正在尝试为类方法编写测试,但是当我调用它们时,我得到一个 AttributeError,它抱怨方法不存在。
class Foo:
@staticmethod
def __method_to_test(x)
return x ** 2
Foo.__method_to_test(3)
最后一行结果如下:AttributeError: type object 'Foo' has no attribute '__method_to_test'
为什么我不能调用该方法?
【问题讨论】:
-
这是一种“私有”方法。称为重整。见,docs.python.org/3/tutorial/classes.html#private-variables
-
@staticmethods!=@classmethod。我不记得@staticmethod在这种情况下是否应该工作,但尝试@classmethod可能会有所帮助。 -
调用
Foo._Foo__method_to_test(3),您会看到该方法仍然存在,但名称不同(以类名和下划线为前缀)。
标签: python attributeerror double-underscore