0

I am getting an error when making a third class that inherits the first two classes' attributes. The first class's function will be go through but when accessing the second class's function I am gettting an error:

class3' object has no attribute 'othernum

Here is the code:

class class1():
    def __init__(self):
        self.number = 10000
    def getNum(self):
        return self.number
    
class class2():
    def __init__(self):
        self.othernum = 1111
    def displaynum(self):
        return self.othernum

class class3(class1, class2):
    pass

newperson = class3()
print(newperson.getNum())
print(newperson.displaynum())

2 Answers2

1

Found the answer.

class class3(class1, class2):
    def __init__(self):
        class1.__init__(self)
        class2.__init__(self)
1

The answer presented by @Ishaan Sathaye is indeed correct. But be aware that there are several mechanisms for initializing base classes in a multiple inheritance hierarchy. See Calling parent class init with multiple inheritance, what's the right way?, in particular the section with heading All base classes are designed for cooperative inheritance.

So, if your 3 classes were designed for cooperative inheritance, we would have:

class class1():
    def __init__(self):
        super().__init__()
        self.number = 10000
    def getNum(self):
        return self.number

class class2():
    def __init__(self):
        super().__init__()
        self.othernum = 1111
    def displaynum(self):
        return self.othernum

class class3(class1, class2):
    def __init__(self):
        super().__init__()

newperson = class3()
print(newperson.getNum())
print(newperson.displaynum())
Booboo
  • 38,656
  • 3
  • 37
  • 60