方法“__init__”中无用的父级或 super() 委托

问题描述 投票:0回答:1
我正在学习《Python 速成课程第二版》一书,我做了他们概述的事情,但他们做了一些在 VS 代码中运行警告的事情 (

Useless parent or super() delegation in method '__init__'

)。他们没有讨论如何修复它,而且我认为它没有任何作用(请告诉我是否有作用),但我不想收到该消息,并且我不想有将来也会发生同样的事情。

这是子类的代码:

class ElectricCar(Car): """A child class of the parent Car, specific to electric cars.""" def __init__(self, make, model, year): """Initialize attributes of the parent class.""" super().__init__(make, model, year)
如果需要的话,这是父类的代码:

class Car: """A class to represent a car.""" def __init__(self, make, model, year): """Initialize attributes to describe a car.""" self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """Return a neatly formatted descriptive name.""" long_name = f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """Print a statement showing the car's mileage.""" print(f"This car has {self.odometer_reading} miles on it.")
感谢您的所有帮助。

附注如果代码块看起来不像代码,我深表歉意。我在选择代码时点击了“代码块”按钮,但是在查看时,它没有语法突出显示(请告诉我我是否做对了,如果不对,下次该怎么做)。

python class inheritance super
1个回答
0
投票
假设您根本没有将

__init__

 添加到您的子类中。父级 
__init__
 尚未被覆盖,将在实例化 
ElectricCar(...)
 时被调用。你的 
ElectricCar.__init__
 没有做任何 python 会做的事情。如果您打算做一些与父类不同的事情,您只需要自己的
__init__

只需删除您的

__init__

 方法即可使警告消失。

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