假设我有类(class) A1 和 A2 和具有 A1/A2 类型元素的类 B。
现在我有一个类B'(B)(它继承自B)。 这个类可以使用A1'和A2'代替A1和A2吗, 这个新类能否以某种方式交换基类中元素的类型?
通常我会说这是不可能的,但因为这是关于 python 的...:P
最佳答案
你是说这样?
class A1(object):
pass
class A1Child(A1):
pass
class A2(object):
pass
class A2Child(A2):
pass
class B(object):
a1_instance = None
a2_instance = None
def __init__(self):
self.a1_instance = A1()
self.a2_instance = A2()
class BChild(B):
def __init__(self):
self.a1_instance = A1Child()
self.a2_instance = A2Child()
b_instance = B()
print b_instance.a1_instance
print b_instance.a2_instance
bchild_instance = BChild()
print bchild_instance.a1_instance
print bchild_instance.a2_instance
关于python - 继承类可以更改基类中元素的类型吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10006299/