首页 > 解决方案 > 在导入的类中调用私有方法

问题描述

我在某些代码中遇到了意外问题,可以在更简单的示例中重现它:

文件1.py

class FirstClass:
    def function1(self):
        print("hello from function1")
    def __function2(self):
        print("hello from function2")

文件2.py

from file1 import FirstClass

fc = FirstClass()

fc.function1()

fc.__function2()

..这就是发生的事情:

$ python file2.py 
hello from function1
Traceback (most recent call last):
  File "file2.py", line 7, in <module>
    fc.__function2()
AttributeError: FirstClass instance has no attribute '__function2'

你能做些什么来使调用__function2起作用?我真的不应该进入那个导入的类并将那个私有方法公开。

标签: pythonpython-3.xclassoop

解决方案


名称以 2 个下划线字符开头的函数不打算从其类外部调用。并且为了允许用户在子类中重新定义它,每个类都调用它的类(不是普通的方法覆盖),它的名称被修改_className__methodName.

所以在这里,你真的不应该直接使用它,但如果你真的需要,你应该能够做到:

fc._FirstClass__function2()

推荐阅读