Saturday 5 December 2015

Python: Inheritance

Inheritance is the concept of re usability. Object of one class can get the properties and methods of object of another class by using inheritance.


Syntax
class DerivedClassName(BaseClassName1, BaseClassName2 ... BaseClassNameN):
    <statement-1>
    .
    .
    .
    <statement-N>


inheritance.py
class Parent:
 def printLastName(self):
  print("Gurram")
 
 def printPermAddress(self):
  print("State : Andhra Pradesh")
  print("Country : India")
 
class Child(Parent):
 def printName(self):
  print("Hari Krishna Gurram")
  
child1 = Child()

child1.printName()
child1.printLastName()
child1.printPermAddress()

$ python3 inheritance.py 
Hari Krishna Gurram
Gurram
State : Andhra Pradesh
Country : India


Observe above program, two classes parent and child are defined. Parent class defines two methods printLastName, printPermAddress.
Child class defines one method printName. Child class inheriting the methods printLastName, printPermAddress from parent class.

Overriding the methods of Parent class
You can override the properties, methods of parent class in child class. For example, following application overrides ‘printPermAddress’ method of Parent class.

inheritance.py

class Parent:
 def printLastName(self):
  print("Gurram")
 
 def printPermAddress(self):
  print("State : Andhra Pradesh")
  print("Country : India")
 
class Child(Parent):
 def printName(self):
  print("Hari Krishna")
  
 def printPermAddress(self):
  print("City : Bangalore")
  print("State : Karnataka")
  print("Country : India")
  
child1 = Child()

child1.printName()
child1.printLastName()
child1.printPermAddress()

$ python3 inheritance.py 
Hari Krishna
Gurram
City : Bangalore
State : Karnataka
Country : India




Previous                                                 Next                                                 Home

No comments:

Post a Comment