0

I am learning multiple inheritance in Python. I have two parent classes Robot and Human. They are being inherited by Cyborg class. I can access the member variable in first class i.e, Robot but unable to access the variables in second BaseClass named Human.

Here is my code.

from abc import abstractmethod, ABC

class Robot(ABC):
    def __init__(self):
        self.computation_level = 70

    @abstractmethod
    def vacuum(self):
        pass

class Human(ABC):
    def __init__(self):
        self.feelings_level = 60

    @abstractmethod
    def run(self):
        pass

class Cyborg(Robot, Human):
    def __init__(self):
        super(Cyborg, self).__init__()

    def vacuum(self):
        print("nothing new in vacuum")

    def run(self):
        print("nothing new in run")


h_obj = Cyborg()
h_obj.vacuum()
h_obj.run()
print(h_obj.computation_level)
print(h_obj.feelings_level)

It returns the following output

nothing new in vacuum
nothing new in run
70
Traceback (most recent call last):
  File "oop.py", line 49, in <module>
    print(h_obj.feelings_level)
AttributeError: 'Cyborg' object has no attribute 'feelings_level'

I have also checked output of Cyborg.mro() which is

[<class '__main__.Cyborg'>, <class '__main__.Robot'>, <class '__main__.Human'>, <class 'abc.ABC'>, <class 'object'>]

Is there any way to access the member variables of second parent class in this case, Human class.

Thanks

  • 2
    `Cyborg.__init__()` only called the inherited method on *one* of its parent classes. For `super()` to work right in the presence of multiple inheritance, you have to use it in *every* class, even the base classes where it doesn't appear to be needed. – jasonharper Mar 26 '22 at 21:00
  • Thanks @jasonharper. It is working now. – NaveedAli92 Mar 26 '22 at 21:06

1 Answers1

1

It maybe of help anyone else, here is the working code. Thanks to @jsonharper

from abc import abstractmethod, ABC
class Human(ABC):
    def __init__(self):
        super(Human, self).__init__()
        self.feelings_level = 60

    @abstractmethod
    def run(self):
        print("hey ")

class Robot(ABC):
    def __init__(self):
        super(Robot, self).__init__()
        self.computation_level = 70

    @abstractmethod
    def vacuum(self):
        print("vaccum")

class Cyborg(Robot, Human):

    def __init__(self):
        super(Cyborg, self).__init__()

    def vacuum(self):
        print("nothing new in vacuum")

    def run(self):
        print("nothing new in run")


h_obj = Cyborg()
h_obj.vacuum()
h_obj.run()
print(h_obj.computation_level)
print(h_obj.feelings_level)