Raja G
Raja G

Reputation: 6633

Python3 , OOP : Multiple classes inheritance into single class

I am Inheriting from multiple parent classes into a single class. What I am trying to do is make a situation of object data conflict.

I mean if two classes hold a variable with same name and different data, which data will be loaded by Python if that variable comes to picture?

what I did

>>> class pac:
...  var=10
...  var2=20
... 
>>> class cac:
...  var3=30
...  var2=10
... 

>>> pob=pac()
>>> cob=cac()
>>> pob.var
10
>>> pob.var2
20
>>> cob.var2
10
>>> cob.var3
30
>>> class newclass(pac,cac):
...  def sum(self):
...   sum=self.var+self.var2
...   sum2=self.var2+self.var3
...   print(sum)
...   print(sum2)
... 
30
50
>>> nob.var
10
>>> nob.var2
20
>>> nob.var3
30
>>> 

It seems like var2 data will consider from parent class : pac instead of cac class.

What needs to be done to make Python consider data from cac instead of pac if same variable name existed with different data? Please do not suggest me to change order of inheritance.

Thank you.

Upvotes: 0

Views: 96

Answers (3)

Yan Li
Yan Li

Reputation: 63

You can set self.var2=cac.var2 in the newclass's init method:

class newclass(pac, cac):
    def __init__(self):
        self.var2 = cac.var2

Upvotes: 2

Gábor Fekete
Gábor Fekete

Reputation: 1358

You could also return a list/tuple of the possible values by using the following code:

@property
    def var2(self):
        key='var2'
        return [getattr(c,key) for c in self.__class__.mro()[1:-1] if hasattr(c,key)]

The mro method returns a list of classes, the first one will be the callers class followed by parents and lastly the object built-in class. This code will return a list of values in the order of inheritance.

Upvotes: 1

acdr
acdr

Reputation: 4706

Without changing the order of inheritance, your subclass will always get an attribute it can find in the first class, from the first class. If you want to find out what the corresponding value is in the second class, you're going to have to explicitly ask for the second class's value.

In your case, something like

class newclass(pac,cac):
    @property
    def var2(self):
        return cac.var2

Note that I'm explicitly asking for cac's var2.

Upvotes: 2

Related Questions