Chapter 14- Inheritance

Example-bag.cpp, Page-544

In [1]:
(false, true)=(0, 1) #enum type
type =['false', 'true']
MAX_ITEMS=25
def IsExist(self, item):
    for i in range(self._Bag__ItemCount):
        if self._Bag__contents[i]==item:
            return true
    return false
def show(self):
    for i in range(self._Bag__ItemCount):
        print self._Bag__contents[i],
    print ""
class Bag:
    __contents=[int]*MAX_ITEMS #protected members
    __ItemCount=int
    def __init__(self):
        self.__ItemCount=0
    def put(self, item):
        self.__contents[self.__ItemCount]=item
        self.__ItemCount+=1
    def IsEmpty(self):
        return true if self.__ItemCount==0 else false
    def IsFull(self):
        return true if self.__ItemCount==MAX_ITEMS else false
    IsExist=IsExist
    show=show
bag=Bag()
item=int
while(true):
    item=int(raw_input("Enter Item Number to be put into the bag <0-no item>: "))
    if item==0:
        break
    bag.put(item)
    print "Items in Bag:",
    bag.show()
    if bag.IsFull():
        print "Bag Full, no more items can be placed"
        break
Enter Item Number to be put into the bag <0-no item>: 1
Items in Bag: 1 
Enter Item Number to be put into the bag <0-no item>: 2
Items in Bag: 1 2 
Enter Item Number to be put into the bag <0-no item>: 3
Items in Bag: 1 2 3 
Enter Item Number to be put into the bag <0-no item>: 3
Items in Bag: 1 2 3 3 
Enter Item Number to be put into the bag <0-no item>: 1
Items in Bag: 1 2 3 3 1 
Enter Item Number to be put into the bag <0-no item>: 0

Example-union.cpp, Page no-548

In [2]:
(false, true)=(0, 1) #enum type
type =['false', 'true']
MAX_ITEMS=25
def IsExist(self, item):
    for i in range(self._Bag__ItemCount):
        if self._Bag__contents[i]==item:
            return true
    return false
def show(self):
    for i in range(self._Bag__ItemCount):
        print self._Bag__contents[i],
    print ""
class Bag:
     #protected members
    __ItemCount=int
    def __init__(self):
        self.__ItemCount=0
        self.__contents=[int]*MAX_ITEMS
    def put(self, item):
        self.__contents[self.__ItemCount]=item
        self.__ItemCount+=1
    def IsEmpty(self):
        return true if self.__ItemCount==0 else false
    def IsFull(self):
        return true if self.__ItemCount==MAX_ITEMS else false
    IsExist=IsExist
    show=show
def read(self):
    while(true):
        element=int(raw_input("Enter Set Element <0-end>: "))
        if element==0:
            break
        self.Add(element)
def add(s1, s2):
    temp = Set()
    temp=s1
    for i in range(s2._Bag__ItemCount):
        if s1.IsExist(s2._Bag__contents[i])==false:
            temp.Add(s2._Bag__contents[i])
    return temp
class Set(Bag):
    def Add(self,element):
        if(self.IsExist(element)==false and self.IsFull()==false):
            self.put(element)
    read=read
    def __assign__(self, s2):
        for i in range(s2._Bag__ItemCount):
            self.__contents[i]=s2.__contents[i]
        self.__ItemCount=s2.__ItemCount
    def __add__(self, s2):
        return add(self, s2)
s1=Set()
s2=Set()
s3=Set()
print "Enter Set 1 elements.."
s1.read()
print "Enter Set 2 elemets.."
s2.read()
s3=s1+s2
print "Union of s1 and s2 :",
s3.show()
Enter Set 1 elements..
Enter Set Element <0-end>: 1
Enter Set Element <0-end>: 2
Enter Set Element <0-end>: 3
Enter Set Element <0-end>: 4
Enter Set Element <0-end>: 0
Enter Set 2 elemets..
Enter Set Element <0-end>: 2
Enter Set Element <0-end>: 4
Enter Set Element <0-end>: 5
Enter Set Element <0-end>: 6
Enter Set Element <0-end>: 0
Union of s1 and s2 : 1 2 3 4 5 6 

Example-cons1.cpp, Page no-558

In [1]:
class B:
    pass
class D(B):
    def msg(self):
        print "No constructors exist in base and derived class"
objd=D()
objd.msg()
No constructors exist in base and derived class

Example-cons2.cpp, Page no-558

In [3]:
class B:
    def __init__(self):
        print "No-argument constructor of base class B is executed"
class D(B):
    pass
objd=D()
No-argument constructor of base class B is executed

Example-cons3.cpp, Page no-559

In [1]:
class B:
    pass
class D(B):
    def __init__(self):
        print "Constructors exist only in derived class"
objd=D()
Constructors exist only in derived class

Example-cons4.cpp, Page no-559

In [4]:
class B:
    def __init__(self):
        print "No-argument constructor of base class B executed first"
class D(B):
    def __init__(self):
        B.__init__(self)
        print "No-argument constructor of derived class D executed next"
objd=D()
No-argument constructor of base class B executed first
No-argument constructor of derived class D executed next

Example-cons5.cpp, Page no-560

In [6]:
class B:
    def __init__(self, a=0):
        if isinstance(a, int):
            print "One-argument constructor of the base class B"
        else:
            print "No-argument constructor of  the base class B"
class D(B):
    def __init__(self, a):
        B.__init__(self, a)
        print "One-argument constructor of the derived class D"
objd=D(3)
One-argument constructor of the base class B
One-argument constructor of the derived class D

Example-cons7.cpp, Page no-561

In [1]:
class B:
    def __init__(self, a):
        print "One-argument constructor of the base class B"
class D(B):
    def __init__(self, a):
        B(a)
        print "One-argument constructor of the derived class D"
objd=D(3)
One-argument constructor of the base class B
One-argument constructor of the derived class D

Example-cons8.cpp, Page no-562

In [2]:
class B1:
    def __init__(self):
        print "No-argument constructor of the base class B1"
class B2:
    def __init__(self):
        B1.__init__(self)
        print "No-argument constructor of the base class B2"
class D(B2, B1):
    def __init__(self):
        B2.__init__(self)
        print "No-argument constructor of the derived class D"
objd=D()
No-argument constructor of the base class B1
No-argument constructor of the base class B2
No-argument constructor of the derived class D

Example-cons9.cpp, Page no-563

In [3]:
class B1:
    def __init__(self):
        print "No-argument constructor of the base class B1"
class B2:
    def __init__(self):
        print "No-argument constructor of the base class B2"
class D(B1, B2):
    def __init__(self):
        B1()
        B2()
        print "No-argument constructor of the derived class D"
objd=D()
No-argument constructor of the base class B1
No-argument constructor of the base class B2
No-argument constructor of the derived class D

Example-cons10.cpp, Page no-563

In [4]:
class B1:
    def __init__(self):
        print "No-argument constructor of the base class B1"
class B2:
    def __init__(self):
        print "No-argument constructor of the base class B2"
class D(B1, B2):
    def __init__(self):
        B2()
        B1()
        print "No-argument constructor of the derived class D"
objd=D()
No-argument constructor of the base class B2
No-argument constructor of the base class B1
No-argument constructor of the derived class D

Example-cons11.cpp, Page no-564

In [5]:
class B:
    def __init__(self):
        print "No-argument constructor of a base class B"
class D1(B):
    def __init__(self):
        B.__init__(self)
        print "No-argument constructor of a base class D1"
class D2(D1):
    def __init__(self):
        D1.__init__(self)
        print "No-argument constructor of a derived class D2"
objd=D2()
No-argument constructor of a base class B
No-argument constructor of a base class D1
No-argument constructor of a derived class D2

Example-cons12.cpp, Page no-566

In [1]:
class B1:
    def __init__(self):
        print "No-argument constructor of the base class B1"
    def __del__(self):
        print "Desctructor in the base class B1"
class B2:
    def __init__(self):
        print "No-argument constructor of the base class B2"
    def __del__(self):
        print "Desctructor in the base class B2"
class D(B1, B2):
    def __init__(self):
        B1.__init__(self)
        B2.__init__(self)
        print "No-argument constructor of the derived class D"
    def __del__(self):
        print "Desctructor in the derived class D"
        for b in self.__class__.__bases__:
            b.__del__(self)
objd=D()
No-argument constructor of the base class B1
No-argument constructor of the base class B2
No-argument constructor of the derived class D

Example-cons13.cpp, Page no-568

In [2]:
class B:
    __x=int
    __y=int
    def __init__(self, a, b):
        self.__x=a
        self.__y=b
class D(B):
    __a=int
    __b=int
    def __init__(self, p, q, r):
        self.__a=p
        B.__init__(self, p, q)
        self.__b=r
    def output(self):
        print "x =", self._B__x
        print "y =", self._B__y
        print "a =", self.__a
        print "b =", self.__b
objd=D(5, 10, 15)
objd.output()
x = 5
y = 10
a = 5
b = 15

Example-runtime.cpp, Page no-570

In [1]:
class B:
    __x=int
    __y=int(0) #initialization
    def __init__(self, a, b):
        self.__x=self.__y+b
        self.__y=a
    def Print(self):
        print "x =", self.__x
        print "y =", self.__y
b = B(2, 3)
b.Print()
x = 3
y = 2

Example-cons14.cpp, Page no-570

In [1]:
class B:
    __x=int
    __y=int
    def read(self):
        self.__x=int(raw_input("X in class B ? "))
        self.__y=int(raw_input("Y in class B ? "))
    def show(self):
        print "X in class B =", self.__x
        print "Y in class B =", self.__y
class D(B):
    __y=int
    __z=int
    def read(self):
        B.read(self)
        self.__y=int(raw_input("Y in class D ? "))
        self.__z=int(raw_input("Z in class D ? "))
    def show(self):
        B.show(self)
        print "Y in class D =", self.__y
        print "Z in class D =", self.__z
        print "Y of B, show from D =", self._B__y
objd=D()
print "Enter data for object of class D.."
objd.read()
print "Contents of object of class D.."
objd.show()
Enter data for object of class D..
X in class B ? 1
Y in class B ? 2
Y in class D ? 3
Z in class D ? 4
Contents of object of class D..
X in class B = 1
Y in class B = 2
Y in class D = 3
Z in class D = 4
Y of B, show from D = 2

Example-stack.cpp, Page no-573

In [1]:
MAX_ELEMENTS=5
class Stack:
    __stack=[int]*(MAX_ELEMENTS+1)
    __StackTop=int
    def __init__(self):
        self.__StackTop=0
    def push(self, element):
        self.__StackTop+=1
        self.__stack[self.__StackTop]=element
    def pop(self, element):
        element=self.__stack[self.__StackTop]
        self.__StackTop-=1
        return element
class MyStack(Stack):
    def push(self, element):
        if self._Stack__StackTop<MAX_ELEMENTS:
            Stack.push(self,element)
            return 1
        print "Stack Overflow"
        return 0
    def pop(self, element):
        if self._Stack__StackTop>0:
            element=Stack.pop(self, element)
            return element
        print "Stack Underflow"
        return 0
stack=MyStack()
print "Enter Integer data to put into the stack..."
while(1):
    element=int(raw_input("Element to Push ? "))
    if stack.push(element)==0:
        break
print "The Stack Contains..."
element=stack.pop(element)
while element:
    print "pop:", element
    element=stack.pop(element)
Enter Integer data to put into the stack...
Element to Push ? 1
Element to Push ? 2
Element to Push ? 3
Element to Push ? 4
Element to Push ? 5
Element to Push ? 6
Stack Overflow
The Stack Contains...
pop: 5
pop: 4
pop: 3
pop: 2
pop: 1
Stack Underflow

Example-exam.cpp, Page no-577

In [3]:
MAX_LEN=25
class person:
    __name=[chr]*MAX_LEN
    __sex=chr
    __age=int
    def ReadData(self):
        self.__name=raw_input("Name ? ")
        self.__sex=str(raw_input("Sex ? "))
        self.__age=int(raw_input("Age ? "))
    def DisplayData(self):
        print "Name:", self.__name
        print "Sex: ", self.__sex
        print "Age: ", self.__age
class student(person):
    __RollNo=int
    __branch=[chr]*20
    def ReadData(self):
        person.ReadData(self) #invoking member function ReadData of base class person
        self.__RollNo=int(raw_input("Roll Number ? "))
        self.__branch=raw_input("Branch Studying ? ")
    def DisplayData(self):
        person.DisplayData(self) #invoking member function DisplayData of base class person
        print "Roll Number:", self.__RollNo
        print "Branch:", self.__branch
class exam(student):
    __Sub1Marks=int
    __Sub2Marks=int
    def ReadData(self):
        student.ReadData(self) #invoking member function ReadData of base class student
        self.__Sub1Marks=int(raw_input("Marks scored in Subject 1 < Max:100> ? "))
        self.__Sub2Marks=int(raw_input("Marks scored in Subject 2 < Max:100> ? "))
    def DisplayData(self):
        student.DisplayData(self) #invoking member function DisplayData of base class student
        print "Marks scored in Subject 1:", self.__Sub1Marks
        print "Marks scored in Subject 2:", self.__Sub2Marks
        print "Total Marks Scored:", self.TotalMarks()
    def TotalMarks(self):
        return self.__Sub1Marks+self.__Sub2Marks
annual=exam()
print "Enter data for Student..."
annual.ReadData()
print "Student Details..."
annual.DisplayData()
Enter data for Student...
Name ? Rajkumar
Sex ? M
Age ? 24
Roll Number ? 9
Branch Studying ? Computer-Technology
Marks scored in Subject 1 < Max:100> ? 92
Marks scored in Subject 2 < Max:100> ? 88
Student Details...
Name: Rajkumar
Sex:  M
Age:  24
Roll Number: 9
Branch: Computer-Technology
Marks scored in Subject 1: 92
Marks scored in Subject 2: 88
Total Marks Scored: 180

Example-mul_inh1.cpp, Page no-580

In [1]:
import sys
class A:
    def __init__(self):
        sys.stdout.write('a'),
class B:
    def __init__(self):
        sys.stdout.write('b'),
class C(A, B):
    def __init__(self):
        A.__init__(self)
        B.__init__(self)
        sys.stdout.write('c'),
objc=C()
abc

Example-mul_inh2.cpp, Page no-581

In [2]:
class A:
    def __init__(self, c):
        sys.stdout.write(c),
class B:
    def __init__(self, b):
        sys.stdout.write(b),
class C(A, B):
    def __init__(self, c1, c2, c3):
        A.__init__(self, c1)
        B.__init__(self, c2)
        sys.stdout.write(c3),
objc=C('a', 'b', 'c')
abc

Example-mul_inh4.cpp, Page no-583

In [1]:
import sys
class A:
    __ch=chr
    def __init__(self, c):
        self.__ch=c
    def show(self):
        sys.stdout.write(self.__ch),
class B:
    __ch=chr
    def __init__(self, b):
        self.__ch=b
    def show(self):
        sys.stdout.write(self.__ch),
class C(A, B):
    __ch=chr
    def __init__(self, c1, c2, c3):
        A.__init__(self, c1)
        B.__init__(self, c2)
        self.__ch=c3
objc=C('a', 'b', 'c')
print "objc.A::show() = ",
A.show(objc)
print "\nobjc.B::show() = ",
B.show(objc)
objc.A::show() = a 
objc.B::show() = b

Example-mul_inh5.cpp, Page no-584

In [1]:
import sys
class A:
    __ch=chr
    def __init__(self, c):
        self.__ch=c
    def show(self):
        sys.stdout.write(self.__ch),
class B:
    __ch=chr
    def __init__(self, b):
        self.__ch=b
    def show(self):
        sys.stdout.write(self.__ch),
class C(A, B):
    __ch=chr
    def __init__(self, c1, c2, c3):
        A.__init__(self, c1)
        B.__init__(self, c2)
        self.__ch=c3
    def show(self):
        A.show(self)
        B.show(self)
        sys.stdout.write(self.__ch),
objc=C('a', 'b', 'c')
print "objc.show() = ",
objc.show()
print "\nobjc.C::show() = ",
C.show(objc)
print "\nobjc.A::show() = ",
A.show(objc)
print "\nobjc.B::show() = ",
B.show(objc)
objc.show() = abc 
objc.C::show() = abc 
objc.A::show() = a 
objc.B::show() = b

Example-publish1.cpp, Page no-586

In [1]:
class publication:
    __title=[chr]*40
    __price=float
    def getdata(self):
        self.__title=raw_input("\tEnter Title: ")
        self.__price=float(raw_input("\tEnter Price: "))
    def display(self):
        print "\tTitle =", self.__title
        print "\tPrice = %g" %(self.__price)
class sales:
    __PublishSales=[]
    def __init__(self):
        self.__PublishSales=[float]*3
    def getdata(self):
        for i in range(3):
            print "\tEnter Sales of", i+1, "Month: ",
            self.__PublishSales[i]=float(raw_input())
    def display(self):
        TotalSales=0
        for i in range(3):
            print "\tSales of", i+1, "Month = %g" %(self.__PublishSales[i])
            TotalSales+=self.__PublishSales[i]
        print "\tTotalSales = %g" %(TotalSales)
class book(publication, sales):
    __pages=int
    def getdata(self):
        publication.getdata(self)
        self.__pages=int(raw_input("\tEnter Number of Pages: "))
        sales.getdata(self)
    def display(self):
        publication.display(self)
        print "\tNumber of Pages = %g" %(self.__pages)
        sales.display(self)
class tape(publication, sales):
    __PlayTime=int
    def getdata(self):
        publication.getdata(self)
        self.__PlayTime=int(raw_input("\tEnter Playing Time in Minute: "))
        sales.getdata(self)
    def display(self):
        publication.display(self)
        print "\tPlaying Time in Minute = %g" %(self.__PlayTime)
        sales.display(self)
class pamphlet(publication):
    pass
class notice(pamphlet):
    __whom=[chr]*20
    def getdata(self):
        pamphlet.getdata(self)
        self.__whom=raw_input("\tEnter Type of Distributor: ")
    def display(self):
        pamphlet.display(self)
        print "\tType of Distributor =", self.__whom
book1=book()
tape1=tape()
pamp1=pamphlet()
notice1=notice()
print "Enter Book Publication Data..."
book1.getdata()
print "Enter Tape Publication Data..."
tape1.getdata()
print "Enter Pamhlet Publication Data..."
pamp1.getdata()
print "Enter Notice Publication Data..."
notice1.getdata()
print "Book Publication Data..."
book1.display()
print "Tape Publication Data..."
tape1.display()
print "Pamphlet Publication Data..."
pamp1.display()
print "Notice Publication Data..."
notice1.display()
Enter Book Publication Data...
	Enter Title: Microprocessor-x86-Programming
	Enter Price: 180
	Enter Number of Pages: 750
	Enter Sales of 1 Month: 1000
 	Enter Sales of 2 Month: 500
 	Enter Sales of 3 Month: 800
 Enter Tape Publication Data...
	Enter Title: Love-1947
	Enter Price: 100
	Enter Playing Time in Minute: 10
	Enter Sales of 1 Month: 200
 	Enter Sales of 2 Month: 500
 	Enter Sales of 3 Month: 400
 Enter Pamhlet Publication Data...
	Enter Title: Advanced-Computing-95-Conference
	Enter Price: 10
Enter Notice Publication Data...
	Enter Title: General-Meeting
	Enter Price: 100
	Enter Type of Distributor: Retail
Book Publication Data...
	Title = Microprocessor-x86-Programming
	Price = 180
	Number of Pages = 750
	Sales of 1 Month = 1000
	Sales of 2 Month = 500
	Sales of 3 Month = 800
	TotalSales = 2300
Tape Publication Data...
	Title = Love-1947
	Price = 100
	Playing Time in Minute = 10
	Sales of 1 Month = 200
	Sales of 2 Month = 500
	Sales of 3 Month = 400
	TotalSales = 1100
Pamphlet Publication Data...
	Title = Advanced-Computing-95-Conference
	Price = 10
Notice Publication Data...
	Title = General-Meeting
	Price = 100
	Type of Distributor = Retail

Example-vehicle.cpp, Page no-591

In [4]:
MAX_LEN=25
class Vehicle:
    __name=[chr]*MAX_LEN
    __WheelsCount=int
    def GetData(self):
        self.__name=raw_input("Name of the Vehicle ? ")
        self.__WheelsCount=int(raw_input("Wheels ? "))
    def DisplayData(self):
        print "Name of the Vehicle :", self.__name 
        print "Wheels :", self.__WheelsCount
class LightMotor(Vehicle):
    __SpeedLimit=int
    def GetData(self):
        Vehicle.GetData(self)
        self.__SpeedLimit=int(raw_input("Speed Limit ? "))
    def DisplayData(self):
        Vehicle.DisplayData(self)
        print "Speed Limit :", self.__SpeedLimit
class HeavyMotor(Vehicle):
    __permit=[chr]*MAX_LEN
    __LoadCapacity=int
    def GetData(self):
        Vehicle.GetData(self)
        self.__LoadCapacity=int(raw_input("Load Carrying Capacity ? "))
        self.__permit=raw_input("Permit Type ? ")
    def DisplayData(self):
        Vehicle.DisplayData(self)
        print "Load Carrying Capacity : ", self.__LoadCapacity 
        print "Permit:", self.__permit
class GearMotor(LightMotor):
    __GearCount=int
    def GetData(self):
        LightMotor.GetData(self)
        self.__GearCount=int(raw_input("No. of Gears ? "))
    def DisplayData(self):
        LightMotor.DisplayData(self)
        print "Gears :", self.__GearCount
class NonGearMotor(LightMotor):
    def GetData(self):
        LightMotor.Getdata(self)
    def DisplayData(self):
        LightMotor.DisplayData(self)
class Passenger(HeavyMotor):
    __sitting=int
    __standing=int
    def GetData(self):
        HeavyMotor.GetData(self)
        self.__sitting=int(raw_input("Maximum Seats ? "))
        self.__standing=int(raw_input("Maximum Standing ? "))
    def DisplayData(self):
        HeavyMotor.DisplayData(self)
        print "Maximum Seats:", self.__sitting
        print "Maximum Standing:", self.__standing
class Goods(HeavyMotor):
    def GetData(self):
        HeavyMotor.Getdata(self)
    def DisplayData(self):
        HeavyMotor.DisplayData(self)
vehi1=GearMotor()
vehi2=Passenger()
print "Enter Data for Gear Motor Vehicle..."
vehi1.GetData()
print "Enter Data for Passenger Motor Vehicle..."
vehi2.GetData()
print "Data of Gear Motor Vehicle..."
vehi1.DisplayData()
print "Data of Passenger Motor Vehicle..."
vehi2.DisplayData()
Enter Data for Gear Motor Vehicle...
Name of the Vehicle ? Maruti-Car
Wheels ? 4
Speed Limit ? 4
No. of Gears ? 5
Enter Data for Passenger Motor Vehicle...
Name of the Vehicle ? KSRTC-BUS
Wheels ? 4
Load Carrying Capacity ? 60
Permit Type ? National
Maximum Seats ? 45
Maximum Standing ? 60
Data of Gear Motor Vehicle...
Name of the Vehicle : Maruti-Car
Wheels : 4
Speed Limit : 4
Gears : 5
Data of Passenger Motor Vehicle...
Name of the Vehicle : KSRTC-BUS
Wheels : 4
Load Carrying Capacity :  60
Permit: National
Maximum Seats: 45
Maximum Standing: 60

Example-int_ext.cpp, Page no-595

In [1]:
MAX_LEN=25
class student():
    __RollNo=int
    __branch=[chr]*20
    def ReadStudentData(self):
        self.__RollNo=int(raw_input("Roll Number ? "))
        self.__branch=raw_input("Branch Studying ? ")
    def DisplayStudentData(self):
        print "Roll Number:", self.__RollNo
        print "Branch:", self.__branch
class InternalExam(student):
    __Sub1Marks=int
    __Sub2Marks=int
    def ReadData(self):
        self.__Sub1Marks=int(raw_input("Marks scored in Subject 1 < Max:100> ? "))
        self.__Sub2Marks=int(raw_input("Marks scored in Subject 2 < Max:100> ? "))
    def DisplayData(self):
        print "Internal Marks scored in Subject 1:", self.__Sub1Marks
        print "Internal Marks scored in Subject 2:", self.__Sub2Marks
        print "Internal Total Marks Scored:", self.TotalMarks()
    def InternalTotalMarks(self):
        return self.__Sub1Marks+self.__Sub2Marks
class ExternalExam(student):
    __Sub1Marks=int
    __Sub2Marks=int
    def ReadData(self):
        self.__Sub1Marks=int(raw_input("Marks scored in Subject 1 < Max:100> ? "))
        self.__Sub2Marks=int(raw_input("Marks scored in Subject 2 < Max:100> ? "))
    def DisplayData(self):
        print "External Marks scored in Subject 1:", self.__Sub1Marks
        print "External Marks scored in Subject 2:", self.__Sub2Marks
        print "External Total Marks Scored:", self.ExternalTotalMarks()
    def ExternalTotalMarks(self):
        return self.__Sub1Marks+self.__Sub2Marks
class result(InternalExam, ExternalExam):
    __total=int
    def TotalMarks(self):
        return InternalExam.InternalTotalMarks(self)+ExternalExam.ExternalTotalMarks(self)
student1=result()
print "Enter data for Student1..."
student1.ReadStudentData()
print "Enter internal marks..."
InternalExam.ReadData(student1)
print "Enter external marks..."
ExternalExam.ReadData(student1)
print "Student Details..."
student1.DisplayStudentData()
InternalExam.DisplayData(student1)
ExternalExam.DisplayData(student1)
print "Total Marks =", student1.TotalMarks()
Enter data for Student1...
Roll Number ? 9
Branch Studying ? Computer-Technology
Enter internal marks...
Marks scored in Subject 1 < Max:100> ? 80
Marks scored in Subject 2 < Max:100> ? 85
Enter external marks...
Marks scored in Subject 1 < Max:100> ? 89
Marks scored in Subject 2 < Max:100> ? 90
Student Details...
Roll Number: 9
Branch: Computer-Technology
Internal Marks scored in Subject 1: 80
Internal Marks scored in Subject 2: 85
Internal Total Marks Scored: 344
External Marks scored in Subject 1: 89
External Marks scored in Subject 2: 90
External Total Marks Scored: 179
Total Marks = 344

Example-vir.cpp, Page no-598

In [1]:
class A:
    __x=int
    def __init__(self, i=None):
        if isinstance(i, int):
            self.__x=i
        else:
            self.__x=-1
    def geta(self):
        return self.__x
class B(A):
    __y=int
    def __init__(self, i, k):
        A.__init__(self, i)
        self.__y=k
    def getb(self):
        return self.__y
    def show(self):
        print self._A__x, self.geta(), self.getb()
class C(A):
    __z=int
    def __init__(self, i, k):
        A.__init__(self, i)
        self.__z=k
    def getc(self):
        return self.__z
    def show(self):
        print self._A__x, self.geta(), self.getc()
class D(B,C):
    def __init__(self, i, j):
        B.__init__(self, i, j)
        C.__init__(self, i, j)
    def show(self):
        print self._A__x, self.geta(), self.getb(), self.getc(), self.getc()
d1=D(3, 5)
print "Object d1 contents:",
d1.show() #unlike C++, python executes the 1 argument constuctor of A() instead of implicit call to the no argument constructor of A()
b1=B(7, 9)
print "Object b1 contents:",
b1.show()
c1=C(11, 13)
print "Object c1 contents:",
c1.show()
Object d1 contents: 3 3 5 5 5
Object b1 contents: 7 7 9
Object c1 contents: 11 11 13

Example-sports.cpp, Page no-601

In [1]:
MAX_LEN=25
class person:
    __name=[chr]*MAX_LEN
    __sex=chr
    __age=int
    def ReadPerson(self):
        self.__name=raw_input("Name ? ")
        self.__sex=str(raw_input("Sex ? "))
        self.__age=int(raw_input("Age ? "))
    def DisplayPerson(self):
        print "Name:", self.__name
        print "Sex: ", self.__sex
        print "Age: ", self.__age
class sports(person):
    __name=[chr]*MAX_LEN
    __score=int
    def ReadData(self):
        self.__name=raw_input("Game Played ? ")
        self.__score=int(raw_input("Game Score ? "))
    def DisplayData(self):
        print "Sports Played:", self.__name
        print "Game Score: ", self.__score
    def SportsScore(self):
        return self.__score
class student(person):
    __RollNo=int
    __branch=[chr]*20
    def ReadData(self):
        self.__RollNo=int(raw_input("Roll Number ? "))
        self.__branch=raw_input("Branch Studying ? ")
    def DisplayData(self):
        print "Roll Number:", self.__RollNo
        print "Branch:", self.__branch
class exam(student):
    __Sub1Marks=int
    __Sub2Marks=int
    def ReadData(self):
        self.__Sub1Marks=int(raw_input("Marks scored in Subject 1 < Max:100> ? "))
        self.__Sub2Marks=int(raw_input("Marks scored in Subject 2 < Max:100> ? "))
    def DisplayData(self):
        print "Marks scored in Subject 1:", self.__Sub1Marks
        print "Marks scored in Subject 2:", self.__Sub2Marks
        print "Total Marks Scored:", self.TotalMarks()
    def TotalMarks(self):
        return self.__Sub1Marks+self.__Sub2Marks
class result(exam, sports):
    __total=int
    def ReadData(self):
        self.ReadPerson()
        student.ReadData(self)
        exam.ReadData(self)
        sports.ReadData(self)
    def DisplayData(self):
        self.DisplayPerson()
        student.DisplayData(self)
        exam.DisplayData(self)
        sports.DisplayData(self)
        print "Overall Performance, (exam + sports) :",self.Percentage(), "%"
    def Percentage(self):
        return (exam.TotalMarks(self)+self.SportsScore())/3
Student=result()
print "Enter data for Student..."
Student.ReadData()
print "Student Details..."
Student.DisplayData()
Enter data for Student...
Name ? Rajkumar
Sex ? M
Age ? 24
Roll Number ? 9
Branch Studying ? Computer-Technology
Marks scored in Subject 1 < Max:100> ? 92
Marks scored in Subject 2 < Max:100> ? 88
Game Played ? Cricket
Game Score ? 85
Student Details...
Name: Rajkumar
Sex:  M
Age:  24
Roll Number: 9
Branch: Computer-Technology
Marks scored in Subject 1: 92
Marks scored in Subject 2: 88
Total Marks Scored: 180
Sports Played: Cricket
Game Score:  85
Overall Performance, (exam + sports) : 88 %

Example-nesting.cpp, Page no-605

In [1]:
class B:
    num=int
    def __init__(self, a=None):
        if isinstance(a, int):
            print "Constructor B( int a ) is invoked"
            self.num=a
        else:
            self.num=0
class D:
    data1=int
    objb=B()
    def __init__(self, a):
        self.objb.__init__(a)
        self.data1=a
    def output(self):
        print "Data in Object of Class S =", self.data1
        print "Data in Member object of class B in class D = ",self.objb.num
objd = D(10)
objd.output()
Constructor B( int a ) is invoked
Data in Object of Class S = 10
Data in Member object of class B in class D =  10

Example-publish2.cpp, Page no-608

In [1]:
class publication:
    __title=[chr]*40
    __price=float
    def getdata(self):
        self.__title=raw_input("\tEnter Title: ")
        self.__price=float(raw_input("\tEnter Price: "))
    def display(self):
        print "\tTitle =", self.__title
        print "\tPrice = %g" %(self.__price)
class sales:
    __PublishSales=[]
    def __init__(self):
        self.__PublishSales=[float]*3
    def getdata(self):
        for i in range(3):
            print "\tEnter Sales of", i+1, "Month: ",
            self.__PublishSales[i]=float(raw_input())
    def display(self):
        TotalSales=0
        for i in range(3):
            print "\tSales of", i+1, "Month = %g" %(self.__PublishSales[i])
            TotalSales+=self.__PublishSales[i]
        print "\tTotalSales = %g" %(TotalSales)
class book:
    __pages=int
    pub=publication()
    market=sales()
    def getdata(self):
        self.pub.getdata()
        self.__pages=int(raw_input("\tEnter Number of Pages: "))
        self.market.getdata()
    def display(self):
        self.pub.display()
        print "\tNumber of Pages = %g" %(self.__pages)
        self.market.display()
book1=book()
print "Enter Book Publication Data..."
book1.getdata()
print "Book Publication Data..."
book1.display()
Enter Book Publication Data...
	Enter Title: Microprocessor-x86-Programming
	Enter Price: 180
	Enter Number of Pages: 750
	Enter Sales of 1 Month: 1000
 	Enter Sales of 2 Month: 500
 	Enter Sales of 3 Month: 800
 Book Publication Data...
	Title = Microprocessor-x86-Programming
	Price = 180
	Number of Pages = 750
	Sales of 1 Month = 1000
	Sales of 2 Month = 500
	Sales of 3 Month = 800
	TotalSales = 2300

Example-1, Page no-611

In [1]:
class employee:
    emp_id=int
    emp_name=[chr]*30
    def getdata(self):
        self.__emp_id=int(raw_input("Enter employee number: "))
        self.__emp_name=raw_input("Enter emploee name: ")
    def displaydata(self):
        print "Employee Number:", self.__emp_id, "\nEmployee Name:", self.__emp_name
class emp_union:
    __member_id=int
    def getdata(self):
        self.__member_id=int(raw_input("Enter member id: "))
    def displaydata(self):
        print "Member ID:", self.__member_id
class emp_info(employee, emp_union):
    __basic_salary=float
    def getdata(self):
        employee.getdata(self)
        emp_union.getdata(self)
        self.__basic_salary=int(raw_input("Enter basic salary: "))
    def displaydata(self):
        employee.displaydata(self)
        emp_union.displaydata(self)
        print "Basic Salary:", self.__basic_salary
e1=emp_info()
e1.getdata()
e1.displaydata()
Enter employee number: 23
Enter emploee name: Krishnan
Enter member id: 443
Enter basic salary: 8500
Employee Number: 23 
Employee Name: Krishnan
Member ID: 443
Basic Salary: 8500

Example-2, Page no-613

In [2]:
class details:
    __name=[chr]*30
    __address=[chr]*50
    def getdata(self):
        self.__name=raw_input("Name: ")
        self.__address=raw_input("Address: ")
    def displaydata(self):
        print "Name:", self.__name,"\nAddress:", self.__address
class student(details):
    __marks=float
    def getdata(self):
        details.getdata(self)
        self.__marks=float(raw_input("Percentage Marks: "))
    def displaydata(self):
        details.displaydata(self)
        print "Percentage Marks: %g" %(self.__marks)
class staff(details):
    __salary=float
    def getdata(self):
        details.getdata(self)
        self.__salary=float(raw_input("Salary: "))
    def displaydata(self):
        details.displaydata(self)
        print "Salary: %g" %(self.__salary)
student1=student()
staff1=staff()
print "Enter student data:"
student1.getdata()
print "Enter staff data:"
staff1.getdata()
print "Displaying student and staff data:"
student1.displaydata()
staff1.displaydata()
Enter student data:
Name: Venkatesh
Address: H.No. 89, AGM Society, Bangalore
Percentage Marks: 78.4
Enter staff data:
Name: Vijayan
Address: H.No. A-2, SLR Society, Bangalore
Salary: 25000
Displaying student and staff data:
Name: Venkatesh 
Address: H.No. 89, AGM Society, Bangalore
Percentage Marks: 78.4
Name: Vijayan 
Address: H.No. A-2, SLR Society, Bangalore
Salary: 25000