Chapter 10- Classes and objects

Example- student.cpp, Page no-344

In [1]:
class student: #member functions definition inside the body
    __roll_no=int
    __name=[None]*20
    def setdata(self, roll_no_in, name_in):
        self.roll_no=roll_no_in
        self.name=name_in
    def outdata(self):
        print "Roll no =", self.roll_no
        print "Name =", self.name
s1=student() #object of class student
s2=student()
s1.setdata(1, "Tejaswi") #invoking member functions
s2.setdata(10, "Rajkumar")
print "Student details..."
s1.outdata()
s2.outdata()
Student details...
Roll no = 1
Name = Tejaswi
Roll no = 10
Name = Rajkumar

Example-rect.cpp, Page no-345

In [1]:
class rect:
    __length=int
    __breadth=int
    def read(self, i, j):
        self.__length=i
        self.__breadth=j
    def area(self):
        return self.__length*self.__breadth
r=rect()
x, y=[int(x) for x in raw_input("Enter the length and breadth of the reactangle: ").split()]
r.read(x,y)
print "Area of the rectangle =", r.area()
Enter the length and breadth of the reactangle: 4 10
Area of the rectangle = 40

Example-date1.cpp, Page no-348

In [1]:
class date:
    __day=int
    __month=int
    __year=int
    def Set(self, DayIn, MonthIn, YearIn):
        self.__day=DayIn
        self.__month=MonthIn
        self.__year=YearIn
    def show(self):
        print "%s-%s-%s" %(self.__day, self.__month, self.__year)
d1=date()
d2=date()
d3=date()
d1.Set(26, 3, 1958)
d2.Set(14, 4, 1971)
d3.Set(1, 9, 1973)
print "Birth Date of First Author: ",
d1.show()
print "Birth Date of Second Author: ",
d2.show()
print "Birth Date of Third Author: ",
d3.show()
Birth Date of First Author:  26-3-1958
Birth Date of Second Author:  14-4-1971
Birth Date of Third Author:  1-9-1973

Example-date2.cpp, Page no-350

In [2]:
def Set(self, DayIn, MonthIn, YearIn):
    self.__day=DayIn
    self.__month=MonthIn
    self.__year=YearIn
def show(self):
    print "%s-%s-%s" %(self.__day, self.__month, self.__year)
class date:
    __day=int
    __month=int
    __year=int
    Set=Set #definiton of member function outside the class
    show=show
d1=date()
d2=date()
d3=date()
d1.Set(26, 3, 1958)
d2.Set(14, 4, 1971)
d3.Set(1, 9, 1973)
print "Birth Date of First Author: ",
d1.show()
print "Birth Date of Second Author: ",
d2.show()
print "Birth Date of Third Author: ",
d3.show()
Birth Date of First Author:  26-3-1958
Birth Date of Second Author:  14-4-1971
Birth Date of Third Author:  1-9-1973

Example-date3.cpp, Page no-352

In [3]:
def Set(self, DayIn, MonthIn, YearIn):
    self.__day=DayIn
    self.__month=MonthIn
    self.__year=YearIn
def show(self):
    print self.__day, "-", self.__month, "-", self.__year
class date:
    __day=int
    __month=int
    __year=int
    Set=Set
    show=show
d1=date()
d2=date()
d3=date()
d1.Set(26, 3, 1958)
d2.Set(14, 4, 1971)
d3.Set(1, 9, 1973)
print "Birth Date of First Author: ",
d1.show()
print "Birth Date of Second Author: ",
d2.show()
print "Birth Date of Third Author: ",
d3.show()
Birth Date of First Author:  26 - 3 - 1958
Birth Date of Second Author:  14 - 4 - 1971
Birth Date of Third Author:  1 - 9 - 1973

Example-nesting.cpp, Page no-354

In [4]:
class NumberParis:
    __num1=int
    __num2=int
    def read(self):
        self.__num1=int(raw_input("Enter First Number: "))
        self.__num2=int(raw_input("Enter Second Number: "))
    def Max(self):
        if self.__num1>self.__num2:
            return self.__num1
        else:
            return self.__num2
    def ShowMax(self):
        print "Maximum =", self.Max() #invoking a member function in another member function
n1=NumberParis()
n1.read()
n1.ShowMax()
Enter First Number: 5
Enter Second Number: 10
Maximum = 10

Example-part.cpp, Page no-355

In [5]:
class part:
    __ModelNum=int #private members
    __PartNum=int
    __cost=float
    def SetPart(self, mn, pn, c):
        self.__ModelNum=mn
        self.__PartNum=pn
        self.__cost=c
    def ShowPart(self):
        print "Model:", self.__ModelNum
        print "Part:", self.__PartNum
        print "Cost:", self.__cost
p1=part()
p2=part()
p1.SetPart(1996, 23, 1250.55)
p2.SetPart(2000, 243, 2354.75)
print "First Part Details..."
p1.ShowPart()
print "Second Part Details..."
p2.ShowPart()
First Part Details...
Model: 1996
Part: 23
Cost: 1250.55
Second Part Details...
Model: 2000
Part: 243
Cost: 2354.75

Example-vector.cpp, Page no-361

In [10]:
def read(self):
    for i in range(self._vector__sz):
        print "Enter vector [", i, "]? ",
        self._vector__v[i]=int(raw_input())
def show_sum(self):
    Sum=0
    for i in range(self._vector__sz):
        Sum+=self._vector__v[i]
    print "Vector sum =", Sum
class vector:
    __v=[int] #array of type integer
    __sz=int
    def VectorSize(self, size):
        self.__sz= size
        self.__v=[int]*size #dynamically allocating size to integer array
    def release(self):
        del self.__v
    read=read
    show_sum=show_sum
v1=vector()
count=int(raw_input("How many elements are there in the vector: "))
v1.VectorSize(count)
v1.read()
v1.show_sum()
v1.release()
How many elements are there in the vector: 5
Enter vector [ 0 ]? 1
 Enter vector [ 1 ]? 2
 Enter vector [ 2 ]? 3
 Enter vector [ 3 ]? 4
 Enter vector [ 4 ]? 5
 Vector sum = 15

Example-distance.cpp, Page no-363

In [11]:
class distance:
    __feet=float
    __inches=float
    def init(self, ft, In):
        self.__feet=ft
        self.__inches=In
    def read(self):
        self.__feet=float(raw_input("Enter feet: "))
        self.__inches=float(raw_input("Enter inches: "))
    def show(self):
        print self.__feet, "\'-", self.__inches, "\""
    def add(self, d1, d2):
        self.__feet=d1.__feet+d2.__feet
        self.__inches=d1.__inches+d2.__inches
        if self.__inches>=12:
            self.__feet=self.__feet+1
            self.__inches=self.__inches-12
d1=distance()
d2=distance()
d3=distance()
d2.init(11, 6.25)
d1.read()
print "d1=",
d1.show()
print "d2=",
d2.show()
d3.add(d1,d2)
print "d3 = d1+d2 =",
d3.show()
Enter feet: 12.0
Enter inches: 7.25
d1= 12.0 '- 7.25 "
d2= 11 '- 6.25 "
d3 = d1+d2 = 24.0 '- 1.5 "

Example-account.cpp, Page no-365

In [12]:
def MoneyTransfer(self, acc , amount): # passing objects as parameters
        self._AccClass__balance=self._AccClass__balance-amount
        acc._AccClass__balance=acc._AccClass__balance + amount
class AccClass:
    __accno=int
    __balance=float
    def setdata(self, an, bal=0.0):
        self.accno=an
        self.__balance=bal
    def getdata(self):
        self.accno=raw_input("Enter account number for acc1 object: ")
        self.__balance=float(raw_input("Enter the balance: "))
    def display(self):
        print "Acoount number is: ", self.accno
        print "Balance is: ", self.__balance
    MoneyTransfer=MoneyTransfer
acc1=AccClass()
acc2=AccClass()
acc3=AccClass()
acc1.getdata()
acc2.setdata(10)
acc3.setdata(20, 750.5)
print "Acoount information..."
acc1.display()
acc2.display()
acc3.display()
trans_money=float(raw_input("How much money is to be transferred from acc3 to acc1: "))
acc3.MoneyTransfer(acc1, trans_money)
print "Updated information about accounts..."
acc1.display()
acc2.display()
acc3.display()
Enter account number for acc1 object: 1
Enter the balance: 100
Acoount information...
Acoount number is:  1
Balance is:  100.0
Acoount number is:  10
Balance is:  0.0
Acoount number is:  20
Balance is:  750.5
How much money is to be transferred from acc3 to acc1: 200
Updated information about accounts...
Acoount number is:  1
Balance is:  300.0
Acoount number is:  10
Balance is:  0.0
Acoount number is:  20
Balance is:  550.5

Example-complex.cpp, Page no-367

In [13]:
import math
def add (self, c2): #objects as parameters 
    temp=Complex()
    temp._Complex__real=self._Complex__real+c2._Complex__real
    temp._Complex__imag=self._Complex__imag+c2._Complex__imag
    return temp
class Complex:
    __real=float
    __imag=float
    def getdata(self):
        self.__real=float(raw_input("Real Part ? "))
        self.__imag=float(raw_input("Imag Part ? "))
    def outdata(self, msg):
        print msg, 
        print self.__real,
        if self.__imag<0:
            print "-i",
        else:
            print "+i",
        print math.fabs(self.__imag) #print absolute value
    add=add
c1=Complex()
c2=Complex()
c3=Complex()
print "Enter Complex number c1..."
c1.getdata()
print "Enter Complex number c2..."
c2.getdata()
c3=c1.add(c2)
c3.outdata("c3=c1.add(c2):")
Enter Complex number c1...
Real Part ? 1.5
Imag Part ? 2
Enter Complex number c2...
Real Part ? 3
Imag Part ? -4.3
c3=c1.add(c2): 4.5 -i 2.3

Example-friend1.cpp, Page no-371

In [1]:
class one:
    __data1=int
    def setdata(self, init):
        self.__data1=init
class two:
    __data2=int
    def setdata(self, init):
        self.__data2=init
def add_both(a, b): #friend function
    return a._one__data1+b._two__data2
a=one()
b=two()
a.setdata(5)
b.setdata(10)
print "Sum of one and two:", add_both(a,b)
Sum of one and two: 15

Example-friend2.cpp, Page no-373

In [2]:
class boy:
    __income1=int
    __income2=int
    def setdata(self, in1, in2):
        self.__income1=in1
        self.__income2=in2
class girl:
    __income=int
    def girlfunc(self, b1):
        return b1._boy__income1+b1._boy__income2
    def setdata(self, In):
        self.__income=In
    def show(self):
        b1=boy()
        b1.setdata(100, 200)
        print "boy's Income1 in show():", b1._boy__income1
        print "girl's income in show():", self.__income
b1=boy()
g1=girl()
b1.setdata(500, 1000)
g1.setdata(300)
print "boy b1 total income:", g1.girlfunc(b1)
g1.show()
boy b1 total income: 1500
boy's Income1 in show(): 100
girl's income in show(): 300

Example-friend3.cpp, Page no-375

In [3]:
def girlfunc(self, b1):
        return b1._boy__income1+b1._boy__income2
class girl:
    __income=int
    __girlfunc=girlfunc
    def setdata(self, In):
        self.__income=In
    def show(self):
        print "girl income:", self.__income
class boy:
    __income1=int
    __income2=int
    def setdata(self, in1, in2):
        self.__income1=in1
        self.__income2=in2
b1=boy()
g1=girl()
b1.setdata(500, 1000)
g1.setdata(300)
print "boy b1 total income:", g1._girl__girlfunc(b1)
g1.show()
boy b1 total income: 1500
girl income: 300

Example-constmem.cpp, Page 377

In [1]:
def __init__(self):
    self._Person__name=self._Person__address=self._Person__phone=0
def clear(self):
    del self._Person__name
    del self._Person__address
    del self._Person__phone
def setname(self, Str):
    if self._Person__name:
        del self._Person__name
    self._Person__name=Str
def setaddress(self, Str):
    if self._Person__address:
        del self._Person__address
    self._Person__address=Str
def setphone(self, Str):
    if self._Person__phone:
        del self._Person__phone
    self._Person__phone=Str
def getname(self):
    return self._Person__name
def getaddress(self):
    return self._Person__address
def getphone(self):
    return self._Person__phone
def printperson(p):
    if p.getname():
        print "Name :", p.getname()
    if p.getaddress():
        print "Address :", p.getaddress()
    if p.getphone():
        print "Phone :", p.getphone()
class Person:
    __name=str
    __address=str
    __phone=str
    __init__=__init__
    clear=clear
    setname=setname
    setaddress=setaddress
    setphone=setphone
    getname=getname
    getaddress=getaddress
    getphone=getphone
p1=Person()
p2=Person()
p1.setname("Rajkumar")
p1.setaddress("Email: rajacdacb.ernet.in")
p1.setphone("90-080-5584271")
printperson(p1)
p2.setname("Venugopal K R")
p2.setaddress("Bangalore University")
p2.setphone("-not sure-")
printperson(p2)
p1.clear()
p2.clear()
Name : Rajkumar
Address : Email: rajacdacb.ernet.in
Phone : 90-080-5584271
Name : Venugopal K R
Address : Bangalore University
Phone : -not sure-

Example-count.cpp, Page no-382

In [1]:
class MyClass():
    __count=[int]#static member
    __number=int
    def set(self, num):
        self.__number=num
        self.__count[0]+=1
    def show(self):
        print "Number of calls made to 'set()' through any object:", self.__count[0]
obj1=MyClass()
obj1._MyClass__count[0]=0
obj1.show()
obj1.set(100)
obj1.show()
obj2=MyClass()
obj3=MyClass()
obj2.set(200)
obj2.show()
obj2.set(250)
obj3.set(300)
obj1.show()
Number of calls made to 'set()' through any object: 0
Number of calls made to 'set()' through any object: 1
Number of calls made to 'set()' through any object: 2
Number of calls made to 'set()' through any object: 4

Example-dirs.cpp, Page no-384

In [1]:
class Directory:
    __path=[str] #static member
    def setpath(self, newpath):
        self.__path[0]=newpath
Directory()._Directory__path[0]="/usr/raj"
print "Path:", Directory()._Directory__path[0]
Directory().setpath("/usr")
print "Path:", Directory()._Directory__path[0]
dir=Directory()
dir.setpath("/etc")
print "Path:", dir._Directory__path[0]
Path: /usr/raj
Path: /usr
Path: /etc

Example Page no-389

In [1]:
class employee:
    __emp_no=int
    __emp_name=[None]*25
    def accept(self, i, j):
        self.__emp_no=i
        self.__emp_name=j
    def display(self):
        print "Employee Number:", self.__emp_no,"\tEmployee Name:",self.__emp_name
e=[]*5
for i in range(5):
    e.append(employee())
print "Enter the details for five employees: "
for i in range(5):
    no=int(raw_input("Number: "))
    name=raw_input("Name: ")
    e[i].accept(no, name)
print "*****Employee Details*****"
for i in range(5):
    e[i].display()
Enter the details for five employees: 
Number: 1
Name: Vishwanathan
Number: 2
Name: Archana
Number: 3
Name: Prasad
Number: 4
Name: Sarthak
Number: 5
Name: Ganeshan
*****Employee Details*****
Employee Number: 1 	Employee Name: Vishwanathan
Employee Number: 2 	Employee Name: Archana
Employee Number: 3 	Employee Name: Prasad
Employee Number: 4 	Employee Name: Sarthak
Employee Number: 5 	Employee Name: Ganeshan