简体   繁体   English

子类无法访问父类定义的实例变量 Class

[英]Subclass Unable to Access Instance Variable Defined by Parent Class

I have created 3 classes which are as follows:我创建了 3 个类,如下所示:

  1. A having a1,a2 as class vairiables A具有a1,a2作为 class 变量
  2. B(A) A is the parent for B , having b1,b2 as class Variables B(A) A 是 B 的父级,具有b1,b2作为 class 变量
  3. C(B) B is the parent for C , having c1, c2 as the class Variables C(B) B 是 C 的父级,具有c1、c2作为 class 变量

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM