How to use parent class object in multiple child class to use all set variables in parent object in children class in python

Viewed 878
class A():
    def __init__(self, a, b):
        self.a = a
        self.b = b

class B(A):
    def __init__(self, c):
        self.c = c

class C(A):
    def __init__(self, d):
        self.d = d


temp = A("japan", "Germany")
childtemp1 = B("California")
childtemp2 = C("Delhi")

After Sometime i am using class B and C for two different purposes but they both have some same common variables which is present in class A and class A is already instantiated.

I am using this class B and C in some more different classes where i want use variables of both class (A and B) and class (A and C).

2 Answers

If you want to access a, b, c using childtemp1 you need to pass a, b, c while creating the object

class A():
    def __init__(self, a, b):
        self.a = a
        self.b = b

class B(A):
    def __init__(self, a, b, c):
        self.c = c
        A.__init__(self, a, b)

class C(A):
    def __init__(self, a, b, d):
        self.d = d
        A.__init__(self, a, b)

childtemp1 = B("Japan", "Germany", "California")
childtemp2 = C("Japan", "Germany", "Delhi")
print(childtemp1.a, childtemp1.b, childtemp1.c)
print(childtemp2.a, childtemp2.b, childtemp2.d)

Output:

Japan Germany California
Japan Germany Delhi

You can create child class using parent object

class A():
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return "a = " + str(self.a) + " b = " + str(self.b) 

class B(A):

    def __init__(self, parent, c):
        self.c = c
        A.__init__(self, parent.a, parent.b)

    def __repr__(self):
      return  super().__repr__()+ " c = " + str(self.c)

class C(A):

    def __init__(self, parent, d):
        self.d = d
        A.__init__(self, parent.a, parent.b)

    def __repr__(self):
        return  super().__repr__()+ " d = " + str(self.d)

temp = A("Japan", "Germany")
childtemp1 = B(temp, 'India')
childtemp2 = C(temp, 'USA')

print(childtemp1)
print(childtemp2)

Output:

a = Japan b = Germany c = India
a = Japan b = Germany d = USA

This example may help you to understand

class A():
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def print_variables(self):
        print(self.a , " ", self.b, end = "  ")

class B(A):
    def __init__(self, a,b,c):
        super(B, self).__init__(a,b)
        self.c = c

    def show(self):
        super(B, self).print_variables()
        print(self.c)

childtemp1 = B("a","b","c")

childtemp1.show()

Output

a   b  c
Related