抱歉,如果我解释得不太好,但我会尽力:
所以我想从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)
您可以尝试将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)
归档时间: |
|
查看次数: |
18005 次 |
最近记录: |