在子 class 中引用实例属性

reference instance attribute in child class

我正在尝试从“父”class (subclass) 调用实例变量到它的“子”class (subsubclass)

class mainclass():
    def __init__(self):
        self.mainclassvar1 = "mainclass"

class subclass(mainclass):
    def __init__(self):
        self.subclassvar1 = "subclass"

    def changeval(self):
        self.subclassvar1 = "subclassedited"

class subsubclass(subclass):
    def __init__(self):
        self.subsubclassvar1 =  subclass.subclassvar1 #<- naturally this fails


def handler():
    main=mainclass()
    sub = subclass()
    sub.changeval()
    subsub = subsubclass()
    print(subsub.subsubclassvar1)# <- how do I achieve this? I would expect "subclassedited" but it doesn't
if __name__ == "__main__":
    handler()

以上显然行不通,但我正在努力展示我想要实现的目标。

如果我将 class subsubclass(subclass) 更改为如下半成品:

class subsubclass(subclass):
    def __init__(self):
        subclass.__init__(self)
        self.subsubclassvar1 =  self.subclassvar1

但是返回值是 subclass 的原始默认值而不是预期的 subclassedited.

我不确定我是否应该尝试这样做,但我有一些代码,逻辑现在已经到了这一点,我想尝试看看我是否可以从中间获得详细信息 class 进入最后一个子节点 class,处于最终修改状态而不是默认状态,并且没有重构大量代码。

每个 __init__ 方法都应调用父级的 __init__ 方法,以便为层次结构中的所有 类 正确初始化实例。

class mainclass:
    def __init__(self):
        super().__init__()
        self.mainclassvar1 = "mainclass"

class subclass(mainclass):
    def __init__(self):
        super().__init__()
        self.subclassvar1 = "subclass"

    def changeval(self):
        self.subclassvar1 = "subclassedited"

class subsubclass(subclass):
    def __init__(self):
        super().__init__()
        # Not sure why you would really need this, but...
        self.subsubclassvar1 =  self.subclassvar1

没有理由,不过 subsub.subclassvar1 应该与 sub.subclassvar1 有关。调用sub.changeval()subsub无关。