Home > Software engineering >  Inheritance from parent class return attribute error
Inheritance from parent class return attribute error

Time:01-03

Hi I tried to inheritance some code from a class :

class MathParent:
    def multiply(self, number1, number2):
        self.answer = number1 * number2
        return self.answer
    def happy(self):
        return "Nice Mark!"

class MathChild(MathParent):
    def plus_x(self, x) :
        return self.answer   x

p_out = MathParent()
print(p_out.multiply(5, 2))
print(p_out.happy())

c_out = MathChild()
print(c_out.happy())
print(c_out.plus_x(5))

that happy methods has successfully inherited, but when I access self.answer attribute, it raise error. I use another way :

return MathParent.self.answer   x

And that still didn't work. Any insight will be very helpful :)

CodePudding user response:

self.answer is only declared whenever multiply is called. You can add constructors as harshraj22 states, but within the existing code, you need to call multiply before calling plus_x.

This:

c_out = MathChild()
print(c_out.happy())
c_out.multiply(1, 1)
print(c_out.plus_x(5))

runs without errors.

CodePudding user response:

self.answer variable is created only when multiply function is run. One way to fix this is, you can use the following to make sure the variable is created once the __init__ is called:


class MathParent:
    def __init__(self) -> None:
        self.answer = 0

    def multiply(self, number1, number2):
        self.answer = number1 * number2
        return self.answer
    def happy(self):
        return "Nice Mark!"

class MathChild(MathParent):
    def plus_x(self, x) :
        return self.answer   x

p_out = MathParent()
print(p_out.multiply(5, 2))
print(p_out.happy())

c_out = MathChild()
print(c_out.happy())
print(c_out.plus_x(5))
  • Related