Python - 覆盖父类参数

时间:2016-10-02 17:58:48

标签: python

我有一个超类和一个子类。

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

问题:

我希望这能用10个燃料初始化一个Car对象,并且位置为(0,0) 但是我不想为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'

1 个答案:

答案 0 :(得分: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类中搜索,当找不到时,它将跳转到Vehicle并找到它。

假设您已在Vehicle类中实现了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)
相关问题