Если вы хотите получить доступ к a, b, c
, используя childtemp1
, вам нужно передать a, b, c
при создании объекта
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)
Вывод:
Japan Germany California
Japan Germany Delhi
Вы можете создать дочерний класс, используя родительский объект
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)
Вывод:
a = Japan b = Germany c = India
a = Japan b = Germany d = USA