2 回答

TA貢獻1875條經驗 獲得超3個贊
如果你想訪問a, b, cusingchildtemp1你需要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

TA貢獻1806條經驗 獲得超5個贊
這個例子可以幫助你理解
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()
輸出
a b c
添加回答
舉報