【问题标题】:Accessing private variable of one class in another class in python在python中访问另一个类中一个类的私有变量
【发布时间】: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


【解决方案1】:

您可以通过更改check 方法来接收B 对象来做到这一点。

试试:

class A:
    def write(self):
        print("hi")

    def check(self,b):
        print(b.get_number())

class B:
    def __init__(self, num):
        self.__number = num

    'accessor method'

    def get_number(self):
        return self.__number

obj = B(100)
a = A()
a.write()
a.check(obj)

【讨论】:

    【解决方案2】:

    在您的代码中,您尝试读取对象 a(属于 A 类)的 __number 字段,而不是 obj(属于 B 类)。

    指令a.check()基本翻译成A.check(self=a)。这意味着在check()-方法中,您将调用B.get_number(self=a),因此get_number()-方法会尝试返回a.__number(不存在)。

    你可能想做的是:

        class A:
            def check(self, other):
                print(B.get_number(other)) # <- NOT "self"!
    
        class B:
            ...
    
        obj = B(100)
        a = A()
        a.write()
        a.check(obj)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 2023-04-07
      • 2020-11-24
      • 1970-01-01
      • 2017-03-22
      • 2014-09-05
      • 1970-01-01
      相关资源
      最近更新 更多