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")
有时我将类 B 和 C 用于两个不同的目的,但它们都有一些相同的公共(public)变量,这些变量存在于类 A 中,并且类 A 已经实例化。
我在一些更多不同的类中使用B类和C类,我想在这些类中使用类(A和B)和类(A和C)的变量。
最佳答案
如果您想使用 childtemp1
访问 a, b, c
,则需要在创建对象时传递 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
关于python - 如何在多个子类中使用父类对象以在python中的子类中使用父类对象中的所有设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61162188/