【问题标题】:AttributeError when trying to access class methods that do exist尝试访问确实存在的类方法时出现 AttributeError
【发布时间】: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


【解决方案1】:

感谢 Sven Eberth,在这里收集他们的回复。

Python 重命名以双下划线开头的方法

以双下划线开头的方法会导致 python 执行名为 name mangling 的操作,这会导致方法从 __method_to_test 重命名为 _Foo__method_to_test

这样调用函数:

Foo._Foo__method_to_test(3)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 2016-11-01
    • 1970-01-01
    • 2021-09-17
    相关资源
    最近更新 更多