Python basic inheritance
This question already has an answer here:
You can call the Car init method and pass its arguments
class ElectricCar(Car):
def __init__(self, model, color, mpg, battery_type):
Car.__init__(self,model,color,mpg)
self.battery_type = battery_type
Or you can also use the super
method which is a preferred approach as mentioned in the comments.
class ElectricCar(Car):
def __init__(self, model, color, mpg, battery_type):
super(ElectricCar,self).__init__(model, color, mpg)
self.battery_type = battery_type
Where is the inheritance in that?
The inheritance lies in what you can do with these classes:
>>> 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.
Notice that you didn't have to write the ElectricCar.display_car()
method.
If you're just inheriting the object class, you are correct in saying you are essentially creating a new class - it just provides a base. In fact, in Python 3.X, this isn't needed at all. Define a class like
class Car:
def __init(self, ...
and the object inheritance goes without saying.
You're on the right track for using it. The real power of inheritance is in building off other predefined classes, such as your ElectricCar inheriting from Car, through a definition such as:
class ElectricCar(Car):
super(ElectricCar, self).__init__()
...
This gives you the functionality of the Car class without having to redefine everything.
Check out the docs on inheritance here for more detailed info.
链接地址: http://www.djcxy.com/p/30038.html下一篇: Python的基本继承