申し訳ありませんが、私はそれだけでなく、それを説明していないが、私は自分のベストを尽くすよ場合:Pythonの継承変数
だから私は、親クラスから変数を継承したいが、私はしたくありません私はそれが冗長だと思うので、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)
これは私が何とかしたいものです::
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)
は、あなたが欲しいものを得ることができません。しかし、あなたは '* args、** kwargs'を使ってほぼそこに行くことができます。 – wim
'eye_color'と' length'はクラス全体ではなく 'Parent'の*インスタンス*に特有です。 'x1 = Parent(" Blue "、2)' '' x2 = Parent( "Green"、3) '' y = Child( "Men") 'が与えられた場合、' 'y.eye_color' 'y.length'は?最低でも、 'Child .__ init__'は引数として' Parent'インスタンスを取る必要があります。 – chepner
親の特性を持つ 'Child'クラスのインスタンスを返す' Parent'クラスに 'create_child'メソッドを作成することができます。だからあなたは 'y = x.create_child()'のように使うことができます –