【问题标题】:Inheritance problem: AttributeError: 'Vector' object has no attribute '_Vector__i'继承问题:AttributeError: 'Vector' 对象没有属性 '_Vector__i'
【发布时间】:2020-03-19 20:29:10
【问题描述】:
    class ComplexNumber:
        # setting a Debug value and will be used to ask user if they want to enter degub mode
        Debug = None
        # initiating variables, self consists of real, imag, and complex. 
        def __init__(self, real,imag):
        #The prefix __ is added to make the variable private
            self.__real = real
            self.__imag = imag
        # Overload '+','-' and '*' to make them compatible for 2 by 2 matrix operation
        def __add__(self, o): 
            return ComplexNumber((self.__real + o.__real),(self.__imag + o.__imag))
        def __sub__(self, o): 
            return ComplexNumber((self.__real - o.__real),(self.__imag - o.__imag))
        def __mul__(self,o):
            return ComplexNumber((self.__real * o.__real - self.__imag * o.__imag),\
        (self.__imag * o.__real + self.__real * o.__imag))

    # Create a child class from ComplexNumber
    class Vector(ComplexNumber):
    #inherit the property of real and image as i and j
        def __init__(self, i,j,k):
           super().__init__(i, j)
           self.k = k
        def __add__(self, o): 
           return Vector((self.__i + o.__i),(self.__j + o.__j),(self.__k + o.__k))

    A = Vector(1,0,3)
    B = Vector(1,0,3)
    print(A+B)

我收到一条错误消息“在 add 中返回 Vector((self.__i + o.__i),(self.__j + o.__j),(self.__k + o.__k) )" AttributeError: 'Vector' 对象没有属性 '_Vector__i'

我想创建一个具有更多属性“k”的新子类,并将 2d add 方法更改为 3d add 方法。我在哪里弄错了这个继承?

【问题讨论】:

  • @chepner 即使没有修改名称,代码也只是错误的——它访问了从未在构造函数中设置的属性。
  • 确实如此,这就是为什么我只发布了指向该问题的链接,而不是将其作为副本关闭。

标签: python inheritance


【解决方案1】:

Vector__add__ 方法中,您无需初始化即可访问属性__i__j。这就是您收到错误的原因。

【讨论】:

  • 我确实找到了问题所在。这是因为我将 self.real 和 self.imag 设置为私有财产。如果我想在子类中使用它们,我需要父类中的类方法来调用该属性。
猜你喜欢
  • 1970-01-01
  • 2021-03-28
  • 2012-05-03
  • 1970-01-01
  • 2019-09-10
  • 1970-01-01
  • 2012-12-01
  • 2021-04-19
相关资源
最近更新 更多