【发布时间】:2020-09-02 07:40:14
【问题描述】:
如何在下面的代码中访问另一个class A 中的class B 的私有变量'number'?
class A:
def write(self):
print("hi")
'It should print the private variable number in class B'
def check(self):
print(B.get_number(self))'error occurs here'
class B:
def __init__(self,num):
self.__number = num
'accessor method'
def get_number(self):
return self.__number
#driver code
obj = B(100)
a = A()
a.write()
a.check()
我得到的错误信息是'A' object has no attribute '_B__number'
【问题讨论】:
-
您不应该访问它。如果您写了
B,请不要使用名称修改来隐藏属性。如果有人else写了B,那么他们隐藏访问权限可能是有原因的。 -
当前错误是因为您将
A的实例传递给需要B实例的函数。
标签: python python-3.x oop private