0
    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)

I received an error saying "in add return Vector((self.__i + o.__i),(self.__j + o.__j),(self.__k + o.__k))" AttributeError: 'Vector' object has no attribute '_Vector__i'

I want to create a new child class with one more property 'k', and change the 2d add method to a 3d add method. Where did I get wrong with this inheritance?

Wei Gong
  • 23
  • 4

1 Answers1

0

In the __add__ method of Vector you access attributes __i and __j without ever having initialized them. That is why you get the error.

user4815162342
  • 141,790
  • 18
  • 296
  • 355
  • I actually find the problem. It is because I set self.real and self.imag as private property. If I want to use them in the child class, I need a class method in parent class to call that property. – Wei Gong Mar 19 '20 at 21:42