很抱歉,如果我不解释它是很好,但我会尽我所能:Python的继承父类变量
所以我想继承父类中的变量,但我不希望在创建Child类的实例时再次传递它们,因为我认为这是多余的。例如,我只想使用Parent的眼睛颜色。请参见下面的示例代码我的意思
这是什么在起作用:
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)
这是我莫名其妙地想:
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)
你不能得到你想要的东西。但是你可以使用'*参数,** kwargs'几乎到达那里。 – wim
'eye_color'和'length'特定于'Parent'的*实例*,而不是整个类。鉴于'x1 =父(“蓝”,2)','x2 =父(“绿”,3)“和”y =子(“男”)','y.eye_color'或'y.length'是?至少,“Child.__ init__”需要将“Parent”实例作为参数。 – chepner
您可以在'Parent'类中创建'create_child'方法,该方法将返回具有父特征的'Child'类的实例。所以你可以像'y = x.create_child()'使用它' –