python - 如何在子类的 __init__() 中附加另一个参数?

标签 python class inheritance

所以基本上我有一个父类,在 init() 中带有一些参数,现在我想定义一个子类,我想在 init() 中重新定义 init()子类只是在其中附加一个新参数。有什么方便的方法可以完成这个吗?

这是我的代码:

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

    def display_car(self):
        #print "This is a "+self.color+" "+self.model+" with "+str(self.mpg)+" MPG."
        print self.condition

    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

my_car = Car("DeLorean", "silver", 88)
my_car = ElectricCar("Fuck me","Gold",998,"molten salt")


print my_car.condition
my_car.drive_car()
print my_car.condition

新参数是battery_type

最佳答案

你可以使用super()来访问父类的__init__()并让父类初始化它的属性。示例-

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

关于python - 如何在子类的 __init__() 中附加另一个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33116450/

相关文章:

c++ - 没有成员函数的结构的继承

python - 模板中的 Django 日期格式 : %B causes "No exception message supplied" error

python - 仅获取一个 MySQL 列作为列表而不是元组

c++ - 在 C++ 头文件中声明重载运算符时遇到问题

c++ - 具有不同模板参数的继承

Android1.5运行时库中的Android资源不被库消费者继承

python - BeautifulSoup 在特定标题后得到表格

python - 如何处理导入错误?

class - Vuejs 在 v-for 中切换类

python - 为什么有些库只编写私有(private)类函数,然后分配一个公共(public)变量来公开它们?