【问题标题】:Python basic inheritance [duplicate]Python基本继承[重复]
【发布时间】:2015-05-24 02:26:36
【问题描述】:

我在理解 Python 中的继承时遇到了困难,但我知道它是如何工作的,因为我在 Java 方面的经验比较丰富......为了清楚起见,我在这里搜索了问题以及在线文档,所以我知道这将立即被标记为重复问题:P

我在 Codecademy 上的代码如下所示:

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

    def display_car(self):
        return "This is a %s %s with %s MPG." % (self.color, self.model, self.mpg)

    def drive_car(self):
        self.condition = "used"

class ElectricCar(Car):
    def __init__(self, model, color, mpg, battery_type):
        self.model = model
        self.color = color
        self.mpg   = mpg
        self.battery_type = battery_type

但据我所见,我几乎是在定义一个新类...其中的继承在哪里?我可以这样做吗:

class ElectricCar(Car):
    def __init__(self, battery_type):
        self.model = model
        self.color = color
        self.mpg   = mpg
        self.battery_type = battery_type

也许有关键字

super

?

【问题讨论】:

    标签: python inheritance overriding


    【解决方案1】:

    您可以调用 Car init 方法并传递其参数

    class ElectricCar(Car):
        def __init__(self, model, color, mpg, battery_type):
            Car.__init__(self,model,color,mpg)
            self.battery_type = battery_type
    

    或者您也可以使用 super 方法,这是 cmets 中提到的首选方法。

    class ElectricCar(Car):
        def __init__(self, model, color, mpg, battery_type):
            super(ElectricCar,self).__init__(model, color, mpg)
            self.battery_type = battery_type
    

    【讨论】:

    • 如果可能,最好使用super()
    • 为什么吃晚饭更受欢迎?当我了解它时,他们一直在使用这种方法。
    • 明白了!我不知道。感谢您的链接
    【解决方案2】:

    如果您只是继承对象类,那么您实际上是在创建一个新类是正确的——它只是提供了一个基础。事实上,在 Python 3.X 中,这根本不需要。定义一个类,如

    class Car:
        def __init(self, ...
    

    对象继承自不必说。

    您在使用它的正确轨道上。继承的真正力量在于构建其他预定义的类,例如通过以下定义从 Car 继承的 ElectricCar:

    class ElectricCar(Car):
        super(ElectricCar, self).__init__()
        ...
    

    这为您提供 Car 类的功能,而无需重新定义所有内容。

    查看关于继承here 的文档了解更多详细信息。

    【讨论】:

      【解决方案3】:

      其中的继承在哪里?

      继承在于你可以用这些类做什么:

      >>> car = Car('Ford Prefect', 'white', 42)
      >>> print(car.display_car())
      This is a white Ford Prefect with 42 MPG.
      >>> electric_car = ElectricCar('Tesla Model S', 'silver', None, 'lead-acid')
      >>> print(electric_car.display_car())
      This is a silver Tesla Model S with None MPG.
      

      请注意,您不必编写 ElectricCar.display_car() 方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-15
        • 1970-01-01
        • 2016-05-03
        • 2016-07-24
        相关资源
        最近更新 更多