在Python子类中设置默认值,OOP?

问题描述 投票:0回答:1

解决方案是

class Vehicle:
    def __init__(self, name, max_speed, mileage):
        self.name = name
        self.max_speed = max_speed
        self.mileage = mileage

    def seating_capacity(self, capacity):
        return f"The seating capacity of a {self.name} is {capacity} passengers"

class Bus(Vehicle):
    # assign default value to capacity
    def seating_capacity(self, capacity=50):
        return super().seating_capacity(capacity=50)

School_bus = Bus("School Volvo", 180, 12)
print(School_bus.seating_capacity())

我不明白:

def seating_capacity(self, capacity=50): ...

为什么他们在子类中重现该方法,然后用 super 返回它?

def seating_capacity(self, capacity=50):
        return super().seating_capacity(capacity=50)
python oop
1个回答
0
投票

此代码在 Python 中使用

method overriding
。 Bus 类重写了从
seating_capacity
继承的
Vehicle
方法。因此,如果用户没有为
capacity
发送任何参数,则将使用默认值。

© www.soinside.com 2019 - 2024. All rights reserved.