The
concept of using properties of one class into another class without creating
object of that class explicitly is known as a Inheritance. A class which is
extended by another class is known as ‘super
class’. A class which is extending another class is known as ‘sub class’. Both super class
properties and sub class properties can be accessed through sub class reference
variable.
Example –
class A:
def m1(self):
self.i=100
class B(A):
def m2(self):
self.j=200
B1=B()
B1.m1()
B1.m2()
print B1.i
print B1.j
def m1(self):
self.i=100
class B(A):
def m2(self):
self.j=200
B1=B()
B1.m1()
B1.m2()
print B1.i
print B1.j
Output –
100
200
Super class properties directly we can use
within the subclass.
Example –
class A:
def m1(self):
self.i=100
class B(A):
def m2(self):
self.j=200
def display(self):
print self.i
print self.j
B1=B()
B1.m1()
B1.m2()
B1.display()
def m1(self):
self.i=100
class B(A):
def m2(self):
self.j=200
def display(self):
print self.i
print self.j
B1=B()
B1.m1()
B1.m2()
B1.display()
Output –
100
200
Example –
class Parent:
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):
def __init__(self):
print 'calling child constructor'
def childMethod(self):
print 'calling child method'
P=Parent()
P.parentMethod()
P.setAttr(200)
P.getAttr()
C=Child()
C.childMethod()
C.parentMethod()
C.setAttr(300)
C.getAttr()
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):
def __init__(self):
print 'calling child constructor'
def childMethod(self):
print 'calling child method'
P=Parent()
P.parentMethod()
P.setAttr(200)
P.getAttr()
C=Child()
C.childMethod()
C.parentMethod()
C.setAttr(300)
C.getAttr()
Output –
calling
parent constructor
calling
parent method
Parent
Attribute 200
calling
child constructor
calling
child method
calling
parent method
Parent Attribute 300
Example –
class A:
def __init__(self):
print 'in constructor of A'
class B(A):
def m1(self):
print 'in m1 of B'
B1=B()
B1.m1()
def __init__(self):
print 'in constructor of A'
class B(A):
def m1(self):
print 'in m1 of B'
B1=B()
B1.m1()
Output –
in
constructor of A
in m1 of B
Example –
class A:
def m1(self):
print A.__bases__
class B(A):
def m2(self):
print B.__bases__
B1=B()
B1.m1()
B1.m2()
def m1(self):
print A.__bases__
class B(A):
def m2(self):
print B.__bases__
B1=B()
B1.m1()
B1.m2()
Output –
()
(<class __main__.A at
0x028BEC00>,)
No comments:
Post a Comment