【发布时间】:2019-06-06 13:42:36
【问题描述】:
我在某些代码中遇到了意外问题,可以在更简单的示例中重现它:
file1.py
class FirstClass:
def function1(self):
print("hello from function1")
def __function2(self):
print("hello from function2")
file2.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 的调用有效?我真的不应该进入那个导入的类并公开那个私有方法。
【问题讨论】:
-
为什么会出乎意料?
-
嗯,这是第一次发生在我身上,这就是我没想到的原因。
-
您可以使用
_FirstClass__function2来完成。如果你必须。我不会打扰健康警告。请参阅此处的私有变量部分:docs.python.org/3.7/tutorial/classes.html -
注意
def __somefunction不是私有方法,它用于避免命名空间冲突,因为python没有访问的隐私模型 -
你可以像说的那样做,但你应该这样做吗?有人为该类建模,认为客户端代码不应访问该“私有”属性。
标签: python python-3.x class oop