繁体   English   中英

Python - 覆盖父类参数

[英]Python - Override parent class argument

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

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 个燃料和 (0, 0) 的位置初始化一个 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'

据我了解您要实现的目标,只需从 Car __init__ 方法中删除“new_position”参数即可。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM