Home > OS >  Is it possible to share value between 2 classes inherited from same class - python
Is it possible to share value between 2 classes inherited from same class - python

Time:10-19

Please find the code below

class Base:
    def __init__(self, **kwargs):
       self.b1 = kwargs['a']
       self.b2 = kwargs['b']

class Child1(Base):
    def __init__(self, **kwargs):
       self.c = kwargs['c']
       super(Child1).__init__(**kwargs)
       print(self.b1)
       print(self.b2)

    def call(self):
       self.b1 -= 10
       self.b2 -= 20

class Child2(Base):
    def __init__(self, **kwargs):
       self.c = kwargs['c']
       super(Child2).__init__(**kwargs)
       print(self.b1)
       print(self.b2)

When I call using the below:

obj1 = Child1(a=20,b=30,c=5)
obj1.call()   #output 20, 30
obj2 = Child2(c=5)

I want the output of b1 and b2 to be reflected since obj1 has already changed the value

Please advice

CodePudding user response:

you can do it like this

class Base:
    instances = []
    def __init__(self, **kwargs):
       self.b1 = kwargs['a']
       self.b2 = kwargs['b']
       Base.instances.append(self)


class Child1(Base):
    def __init__(self, **kwargs):
       self.c = kwargs['c']
       super(Child1,self).__init__(**kwargs)
       print(self.b1)
       print(self.b2)

    def call(self):
       self.b1 -= 10
       self.b2 -= 20


class Child2(Base):
    def __init__(self, **kwargs):
        self.c = kwargs['c']
        super(Child2,self).__init__(a = Base.instances[0].b1, b = Base.instances[0].b2)
        print(self.b1)
        print(self.b2)



obj1 = Child1(a=20,b=30,c=5)
obj1.call()   
obj2 = Child2(c=5)

All new instances initiated with Base are saved inside Base.instances. Then you can take the first one and use its b1 and b2 attributes when you create something from Child2 class.

  • Related