[英]Subclass Unable to Access Instance Variable Defined by Parent Class
I have created 3 classes which are as follows:我创建了 3 个类,如下所示:
I am trying to create an Object for the C(B) class by typing:- obj = C(1,2)我正在尝试通过键入以下内容为 C(B) class 创建一个 Object:- obj = C(1,2)
But I am not able to access the class A, B variables (a1,a2,b1,b2) using the object created from the C class.但是我无法使用从 C class 创建的 object 访问class A、B 变量(a1、a2、b1、b2) 。
class A:
def __init__(self,a1,a2):
self.a1 = a1
self.a2 = a2
def testa():
print('inside A')
class B(A):
def __init__(self,b1,b2):
self.b1 = b1
self.b2 = b2
def testb():
print('inside B')
class C(B):
def __init__(self,c1,c2):
self.c1 = c1
self.c2 = c2
def testc():
print('inside C')
obj = C(1,2)
You have to make the classes communicate.你必须让班级交流。 Here are two alternatives.这里有两种选择。
Alternative 1备选方案 1
class A:
def __init__(self, a1, a2):
self.a1 = a1
self.a2 = a2
print('inside A')
class B(A):
def __init__(self, b1, b2):
super().__init__(b1, b2)
self.b1 = b1
self.b2 = b2
print('inside B')
class C(B):
def __init__(self, c1, c2):
super().__init__(c1, c2)
self.c1 = c1
self.c2 = c2
print('inside C')
obj = C(1, 2)
print(obj.a2, obj.a1) # -> 2 1
print(obj.b2, obj.b1) # -> 2 1
print(obj.c2, obj.c1) # -> 2 1
Alternative 2备选方案 2
class A:
def __init__(self, a1, a2):
self.a1 = a1
self.a2 = a2
print('inside A')
class B(A):
def __init__(self, b1, b2, a1, a2):
A.__init__(self, a1, a2)
self.b1 = b1
self.b2 = b2
print('inside B')
class C(B):
def __init__(self, c1, c2, b1, b2, a1, a2):
B.__init__(self, b1, b2, a1, a2)
self.c1 = c1
self.c2 = c2
print('inside C')
obj = C(6, 5, 4, 3, 2, 1)
print(obj.a2, obj.a1) # -> 1 2
print(obj.b2, obj.b1) # -> 3 4
print(obj.c2, obj.c1) # -> 5 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.