2016-10-02 6 views
-1

私はスーパークラスとサブクラスを持っています。パイソン - オーバーライド親クラスの引数

class Vehicle: 
    def __init__(self, new_fuel, new_position): 
     self.fuel = new_fuel 
     self.position = new_position 

class Car(Vehicle): 
    # Here, I am stating that when Car is initialized, the position will be 
    # at (0, 0), so when you call it, you do not have to give it a new_position argument 
    def __init__(self, new_fuel, new_position=(0, 0)): 
     super(Car, self).__init__(new_fuel, new_position) 
     self.new_position = new_position 

問題:

私はこれが(0、0) の10燃料と位置でCarオブジェクトを初期化したいが、私はnew_positionの引数に入れたくないので、私すべての車が初期化されるとき、それらの位置は(0、0)であると述べました。また、親クラス(ビークル)の引数を変更したくないので、サブクラス(Carなど)内でオーバーライドしたいだけです。

test_car = Car(10) 
print(test_car.new_position) 
>>> (0,0) 

しかし、それは私にこのエラーを与え続け、私の知る限り、あなたが達成しようとしているかを理解としてnew_position

TypeError: __init__() missing 1 required positional argument: 'new_position' 
+0

あなたは –

+1

@MosesKoledoyeは注意掲載コードの正確なコピーを実行していることを確認してください 'new_position'が設定され、position''と同じではありませんスーパークラスで。 – jonrsharpe

+0

@jonrsharpe違いに気付かなかった。うん、そう。 –

答えて

1

の引数に置くことを求めて、単に「new_position」を削除パラメータをCar __init__メソッドから取得します。

class Vehicle: 
    def __init__(self, new_fuel, new_position): 
     self.fuel = new_fuel 
     self.position = new_position 

class Car(Vehicle): 
    # Here, I am stating that when Car is initialized, the position will be 
    # at (0, 0), so when you call it, you do not have to give it a new_position argument 
    def __init__(self, new_fuel): 
     super(Car, self).__init__(new_fuel, new_position= (0, 0)) 

その後Carクラスからの任意の方法は、「位置」の引数が必要になりますときに、Carクラス内で検索すると、見つからない場合は、それが車にジャンプし、それを見つけるでしょう。

はあなたの車クラスでget_position()メソッドを実装しましたことを言うことができます。

class Vehicle: 
    <everything as always> 

    def get_position(self): 
     return self.position 

class Car(Vehicle): 
    <everything as always> 

a = Car(10) 
a.get_position() # Returns (0, 0) 

編集はコメントする:

class Vehicle: 
    def __init__(self, new_fuel): 
     self.fuel = new_fuel 

    def get_position(self): 
     return self.__class__.POSITION 

class Car(Vehicle): 
    POSITION = (0, 0) 
    # Here, I am stating that when Car is initialized, the position will be 
    # at (0, 0), so when you call it, you do not have to give it a new_position argument 
    def __init__(self, new_fuel): 
     super(Car, self).__init__(new_fuel) 

    def new_position(self, value): 
     self.__class__.POSITION = value 

a = Car(10) 
b = Car(20) 
c = Car(30) 

for each in [a, b, c]: 
    print(each.get_position()) 
(0, 0) 
(0, 0) 
(0, 0) 
c.new_position((0, 1)) 
for each in [a, b, c]: 
    print(each.get_position()) 
(0, 1) 
(0, 1) 
(0, 1) 
+0

しかし、私は、出力(0、0)に印刷(test_car.new_position)のために必要。このコードでは、print(test_car.position)のみが(0、0)を出力します。 – Theo

+0

私は私の答えを編集した、しかし、あなたは(だけの車のために利用可能)このメソッドはself.positionと同じように返すようにしたい場合はイムわからないしましたか?はい、これは方法かもしれない場合は – Nf4r

+0

うーん、ない非常に、私はself.positionを返すメソッドを作成する必要はありません。 init内のnew_positionの設定値から位置を返すようにします。 – Theo

関連する問題