- #!/usr/bin/python
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print "Calling parent constructor"
def parentMethod(self):
print 'Calling parent method'
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print "Parent attribute :", Parent.parentAttr
class Child(Parent): # define child class
def __init__(self):
print "Calling child constructor"
def childMethod(self):
print 'Calling child method'
c = Child() # instance of child
c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method Output
Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200- Similar way you can drive a class from multiple parent classes as follows:
class A: # define your class A
.....
class B: # define your calss B
.....
class C(A, B): # subclass of A and B
.....
Auto AdSense
Saturday, 24 January 2015
Python Object Oriented - Class Inheritance
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment