python - 在导入的类中调用私有方法
问题描述
我在某些代码中遇到了意外问题,可以在更简单的示例中重现它:
文件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
起作用?我真的不应该进入那个导入的类并将那个私有方法公开。
解决方案
名称以 2 个下划线字符开头的函数不打算从其类外部调用。并且为了允许用户在子类中重新定义它,每个类都调用它的类(不是普通的方法覆盖),它的名称被修改为_className__methodName
.
所以在这里,你真的不应该直接使用它,但如果你真的需要,你应该能够做到:
fc._FirstClass__function2()
推荐阅读
- python-3.x - Python3对象方法被字典键覆盖
- performance - 无论如何在使用Jmeter的线程中同时运行不同的用户
- r - 有没有一种通用的方法来删除在 R 中以数字开头并以大写字母结尾的子字符串
- c++ - 如何在 C 代码中访问 C++ 结构的 std::string 成员
- haskell - 使用高阶函数查找列表的最大值
- android - 在改造中创建动态对象请求
- r - 如何在 R 的数据框中选择两列?
- mysql - 关闭 ExecutorService 'applicationTaskExecutor'
- python - 为什么 setup.py 被 pip 执行了两次?
- spring-cloud - ZUUL 前置过滤用例(前置过滤应用授权)