Use Inheritance to add more features to a class : Class Inheritance « Class « Python






Use Inheritance to add more features to a class

 

class Car :
    def __init__(self) :
        self.color = "black"
        self.number_of_tires = 4
        self.miles_per_gallon = 20

    def __str__(self) :
        return "Car { Color: "+self.color+" Tires: "+str(self.number_of_tires) \
               +" MPG: " + str(self.miles_per_gallon) + " }"

    def set_color( self, clr ) :
        self.color = clr

    def get_color( self ) :
        return self.color

    def set_number_of_tires( self, nt ) :
        self.number_of_tires = nt

    def get_number_of_tires( self ) :
        return self.number_of_tires

    def set_miles_per_gallon( self, mpg ) :
        self.miles_per_gallon = mpg

    def get_miles_per_gallon( self ) :
        return self.miles_per_gallon

class Hybrid(Car) : #1
  def __init__(self) :
      Car.__init__(self) #2
      self.battery_life = 20

  def __str__(self) :
      s = Car.__str__(self) #3
      s = s + " Battery Life: " + str(self.battery_life)
      return s

  def set_battery_life(self, bl ) :
      self.battery_life = bl

  def get_battery_life(self) :
      return self.battery_life

c = Car()
h = Hybrid()
print h

c = Car()
h = Hybrid()
print c
print h

class ThreeWheelCar(Car) :
    def __init__(self) :
        Car.__init__(self)
        self.number_of_tires = 3

c = Car()
t = ThreeWheelCar()
print c
print t

   
  








Related examples in the same category

1.Use __class__, __bases__ and __dict__ for sub and super classUse __class__, __bases__ and __dict__ for sub and super class
2.Print out class treePrint out class tree
3.Class inheritedClass inherited
4.Inherited methodInherited method
5.Polymorphism: override the function from base class
6.Definition and test function for class Circle which is based on Point class
7.Derived class inheriting from a base class.
8.Multiple Inheritance
9.inheriting from multiple superclasses
10.class extending dict type
11.Class inheritance: inherit member variable override functionClass inheritance: inherit member variable override function