[Python]Append another argument in the __init__() of subclass

So basically I have a parent class with some arguments in the init(), now I want to define a subclass, I want to redefine the init() in the subclass just append a new argument in it. Is there any convenient way to complete this?

Here is my code:

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
    
    def drive_car(self):
        self.condition = "like new"
        
    

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

 

The new argument is

battery_type

 

 

You can use super() to access the parent class’ __init__() and let parent init its attributes . Example –

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

 

//stackoverflow.com/questions/33116450/how-to-append-another-argument-in-the-init-of-subclass

发表评论

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据