Polymorphism
# Vehicle.py
class Vehicle(object):
"""Document String: Define a Vehicle class"""
def __init__(self, brand, year):
self._brand = brand;
self._year = year;
def __str__(self):
return self._brand+' '+str(self._year)
def info(self):
print('Class: %s, %s, %d' % (self.__class__, self._brand, self._year))
# Car.py
from Vehicle import Vehicle;
class Car(Vehicle):
"""Define class Car, which is inherit from class Vehicle"""
def __init__(self, brand, year, model):
"""Construct"""
super(Car, self).__init__(brand, year);
#Vehicle.__init__(self, brand, year);
self.__model = model;
@property
def model(self):
return self.__model
@model.setter
def model(self, value):
self.__model = value
@model.deleter
def model(self):
del self.__model
# override __str__ in Vehicle
def __str__(self):
#return super(Car, self).__str__() + " " + self.model
return Vehicle.__str__(self) + " " + self.model
from Vehicle import Vehicle;
from Car import Car;
def main():
vehicles = [Vehicle("Buick", 1998), Car("Lincoln", 1998, "Continental")]
# Buick 1998 Class: <class 'Vehicle.Vehicle'>, Buick, 1998
# Lincoln 1998 Continental Class: <class 'Car.Car'>, Lincoln, 1998
for v in vehicles:
print(v)
v.info()
if __name__ == '__main__':
main();
Reference
Python How to Program, Chapter 9