如何从Python 3中的内部类访问外部类成员?
下面是我的代码片段 .
class Outer:
def __init__(self):
self.__x = 20
self.__str = "Outer Class"
def show(self):
self.i1 = self.Inner(Outer())
self.i1.display()
def fn(self):
print("Hello from fn() of Outer Class")
print("str : ", self.__str)
class Inner:
def __init__(self, outer):
self.__str_in = "Inner Class"
self.outer = outer
def display(self):
print("str_in : ", self.__str_in)
print("Inside display() of Inner Class")
# print("x : ", self.outer.__x)
# print("str : ", self.outer.__str)
# self.outer.fn()
obj = Outer()
obj.show()
如果我执行注释行,则会抛出错误说 -
line 23, in display
print("x : ", self.outer.__x)
AttributeError: type object 'Outer' has no attribute '_Inner__x'
有人可以帮忙吗?提前致谢 .