Python从父类继承变量

sti*_*re4 6 python class

抱歉,如果我解释得不太好,但我会尽力:

所以我想从Parent类继承变量,但我不想在创建Child类的实例时再次传递它们,因为我认为这是多余的。例如,我只想使用父母的眼睛颜色。请参阅下面的示例代码以了解我的意思

这是有效的:

class Parent:
    def __init__(self, eye_color, length):
        self.eye_color = str(eye_color)
        self.length = length


class Child(Parent):
    def __init__(self, gender, eye_color, length):
        super().__init__(eye_color, length)
        self.gender = str(gender)

x = Parent("Blue", 2)
y = Child("Men", "Blue", 2)

print(x.eye_color, x.length)
print(y.gender, x.length)
Run Code Online (Sandbox Code Playgroud)

这就是我想要的:

class Parent:
    def __init__(self, eye_color, length):
        self.eye_color = str(eye_color)
        self.length = length


class Child(Parent):
    def __init__(self, gender):
        super().__init__(eye_color, length)
        self.gender = str(gender)

x = Parent("Blue", 2)
y = Child("Men")

print(x.length, x.eye_color)
print(y.gender, x.length)
Run Code Online (Sandbox Code Playgroud)

ras*_*sar 2

您可以尝试将Parent实例传递给Child初始值设定项...这可能是您能得到的最接近的结果。

class Parent:
    def __init__(self, eye_color, length):
        self.eye_color = str(eye_color)
        self.length = length


class Child(Parent):
    def __init__(self, gender, parent):
        super().__init__(parent.eye_color, parent.length)
        self.gender = str(gender)

x = Parent("Blue", 2)
y = Child("Men", x)

print(x.length, x.eye_color)
print(y.gender, x.length)
Run Code Online (Sandbox Code Playgroud)

您可以做的另一件事是保存一个last_parent变量:

global last_parent

class Parent:
        def __init__(self, eye_color, length):
            self.eye_color = str(eye_color)
            self.length = length
            last_parent = self


class Child(Parent):
    def __init__(self, gender):
        super().__init__(last_parent.eye_color, last_parent.length)
        self.gender = str(gender)

x = Parent("Blue", 2)
y = Child("Men")

print(x.length, x.eye_color)
print(y.gender, x.length)
Run Code Online (Sandbox Code Playgroud)