Chapter 11: Object Initialization and clean up

Example- bag.cpp, Page-392

In [1]:
MAX_ITEMS=25
def show(self):
    for i in range(self.ItemCount):
        print self._Bag__contents[i],
class Bag:
    __contents=[int]*MAX_ITEMS
    __ItemCount=int
    def SetEmpty(self):
        self.ItemCount=0
    def put(self,item):
        self._Bag__contents[self.ItemCount]=item
        self.ItemCount+=1
    show=show
bag=Bag() #object of class Bag
bag.SetEmpty() #initialize the object
while 1:
    item=int(raw_input("\nEnter Item Number to be put into the bag <0-no item>: "))
    if item==0:
        break
    bag.put(item)
    print "Items in bag:",
    bag.show()
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>: 3
 Items in bag: 1 3
Enter Item Number to be put into the bag <0-no item>: 2
 Items in bag: 1 3 2
Enter Item Number to be put into the bag <0-no item>: 4
 Items in bag: 1 3 2 4
Enter Item Number to be put into the bag <0-no item>: 0

Example- newbag.cpp, Page-395

In [1]:
MAX_ITEMS=25 #size of array contents
def show(self):
    for i in range(self.ItemCount):
        print self._Bag__contents[i],
class Bag:
    __contents=[int]*MAX_ITEMS #int 1D array
    __ItemCount=int
    def __init__(self): #Constructor
        self.ItemCount=0
    def put(self,item): #member function defined inside the class
        self._Bag__contents[self.ItemCount]=item
        self.ItemCount+=1
    show=show #member function defined outside the class
bag=Bag() #object of class Bag
while 1:
    item=int(raw_input("\nEnter Item Number to be put into the bag <0-no item>: "))
    if item==0:
        break
    bag.put(item)
    print "Items in bag:",
    bag.show()
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>: 3
 Items in bag: 1 3
Enter Item Number to be put into the bag <0-no item>: 2
 Items in bag: 1 3 2
Enter Item Number to be put into the bag <0-no item>: 4
 Items in bag: 1 3 2 4
Enter Item Number to be put into the bag <0-no item>: 0

Example-test1.cpp, Page-396

In [1]:
def __init__(self):
    print "Constructor of class test called"
class Test:
    __init__=__init__ #Constructor
G=Test()
def func():
    L=Test()
    print "Here's function func()"
X=Test()
print "main() function"
func()
Constructor of class test called
Constructor of class test called
main() function
Constructor of class test called
Here's function func()

Example- giftbag.cpp, Page- 398

In [1]:
MAX_ITEMS=25
def show(self):
    if self.ItemCount:
        for i in range(self.ItemCount):
            print self._Bag__contents[i],
    else:
        print "Nil"
class Bag:
    __contents=[int]*MAX_ITEMS
    __ItemCount=int
    def __init__(self, item=None): #parameterized constructor: Python does not support overloading of functions
        if isinstance(item, int):
            self._Bag__contents[0]=item
            self.ItemCount=1
        else:
            self.ItemCount=0
    def put(self,item):
        self._Bag__contents[self.ItemCount]=item
        self.ItemCount+=1
    show=show
bag1=Bag()
bag2=Bag(4) #object created using the parameterized constructor
print "Gifted bag1 initially has:",
bag1.show()
print "Gifted bag2 initially has:",
bag2.show()
while 1:
    item=int(raw_input("\nEnter Item Number to be put into the bag <0-no item>: "))
    if item==0:
        break
    bag2.put(item)
    print "Items in bag2:",
    bag2.show()
Gifted bag1 initially has: Nil
Gifted bag2 initially has: 4
Enter Item Number to be put into the bag <0-no item>: 1
 Items in bag2: 4 1
Enter Item Number to be put into the bag <0-no item>: 2
 Items in bag2: 4 1 2
Enter Item Number to be put into the bag <0-no item>: 3
 Items in bag2: 4 1 2 3
Enter Item Number to be put into the bag <0-no item>: 0

Example-test.cpp, Page-400

In [2]:
def __init__(self):
    print "Constructor of class Test called"
def __del__(self):
    print "Destructor of class Test called"
class Test:
    __init__=__init__ #Constructor
    __del__=__del__ #Destructor
x=Test()
print "Terminating main"
Constructor of class Test called
Destructor of class Test called
Terminating main

Example-count.cpp, Page-401

In [1]:
nobjects=0
nobj_alive=0
class MyClass:
    def __init__(self):
        global nobjects #using the global nobjects
        global nobj_alive #using the global nobj_alive
        nobjects+=1
        nobj_alive+=1
    def __del__(self):
        global nobj_alive #using the global nobjects
        nobj_alive-=1
    def show(self):
        global nobjects
        global nobj_alive
        print "Total number of objects created: ", nobjects
        print "Number of objects currently alive: ", nobj_alive
obj1=MyClass()
obj1.show()
def func():
    obj1=MyClass()
    obj2=MyClass()
    obj2.show()
    del obj1
    del obj2
func()
obj1.show()
obj2=MyClass()
obj3=MyClass()
obj2.show()
del obj1
del obj2
del obj3
Total number of objects created:  1
Number of objects currently alive:  1
Total number of objects created:  3
Number of objects currently alive:  3
Total number of objects created:  3
Number of objects currently alive:  1
Total number of objects created:  5
Number of objects currently alive:  3

Example-account.cpp, Page- 403

In [1]:
def MoneyTransfer(self, acc , amount):
        self._AccClass__balance=self._AccClass__balance-amount
        acc._AccClass__balance=acc._AccClass__balance + amount
class AccClass:
    __accno=int
    __balance=float
    def __init__(self, an=None, bal=0.0):
        if isinstance(an, int):
            self.accno=an
            self.__balance=bal
        else:
            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(10)
acc3=AccClass(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-test2.cpp. Page- 405

In [2]:
def __init__(self, NameIn=None):
    if isinstance(NameIn, str):
        self.name=NameIn
        print "Test Object ", NameIn, " created"
    else:
        self.name="unnamed"
        print "Test object 'unnamed' created"
def __del__(self):
    print "Test Object ", self.name, " destroyed"
    del self.name
class Test:
    __name=[str]
    __init__=__init__
    __del__=__del__
g=Test("global")
def func():
    l=Test("func")
    print "here's function func()"
x=Test("main")
func()
print "main() function - termination"
Test Object  global  created
Test Object  global  destroyed
Test Object  main  created
Test Object  main  destroyed
Test Object  func  created
here's function func()
Test Object  func  destroyed
main() function - termination

Example-complex1.cpp, Page- 407

In [1]:
import math
def add (self, c2):
    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 __init__(self, real_in=None, imag_in=0.0):
        if isinstance(real_in, float):
            self.__real=real_in
            self.__imag=imag_in
        else:
            self.__real=self.__imag=0.0
    def show(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(1.5,2.0)
c2=Complex(2.2)
c3=Complex()
c1.show("c1=")
c2.show("c2=")
c3=c1.add(c2)
c3.show("c3=c1.add(c2):")
c1= 1.5 +i 2.0
c2= 2.2 +i 0.0
c3=c1.add(c2): 3.7 +i 2.0

Example- noname.cpp, Page- 410

In [2]:
class nameless:
    __a=int
    def __init__(self):
        print "Constructor"
    def __del__(self):
        print "Destructor"
nameless() #nameless object created
n1=nameless()
n2=nameless()
print "Program terminates"
Constructor
Destructor
Constructor
Destructor
Constructor
Destructor
Program terminates

Example-name.cpp, Page-411

In [1]:
def show(self, msg):
    print msg
    print "First Name: ", self._name__first
    if self._name__middle[0]:
        print "Middle Name: ", self._name__middle
    if self._name__last[0]:
        print "Last Name: ", self._name__last
class name:
    __first=[None]*15
    __middle=[None]*15
    __last=[None]*15
    def __init__(self, FirstName=None, MiddleName=None, LastName=None):
        if isinstance(LastName, str):
            self.__last=LastName
            self.__middle=MiddleName
            self.__first=FirstName
        elif isinstance(MiddleName, str):
            self.__middle=MiddleName
            self.__first=FirstName
        elif isinstance(FirstName, str):
            self.__first=FirstName
        else:
            self.__last='\0' #initialized to NULL
            self.__middle='\0'
            self.__first='\0'
    show=show
n1=name()
n2=name()
n3=name()
n1=name("Rajkumar")
n2=name("Savithri", "S")
n3=name("Veugopal", "K", "R")
n1.show("First prson details...")
n2.show("Second prson details...")
n3.show("Third prson details...")
First prson details...
First Name:  Rajkumar
Second prson details...
First Name:  Savithri
Middle Name:  S
Third prson details...
First Name:  Veugopal
Middle Name:  K
Last Name:  R

Example-vector1.cpp, Page-413

In [1]:
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 __init__(self, size):
        self.__sz= size
        self.__v=[int]*size #dynamically allocating size to integer array
    def __del__(self):
        del self.__v
    read=read
    show_sum=show_sum
count = int
count=int(raw_input("How many elements are there in the vector: "))
v1= vector(count)
v1.read()
v1.show_sum()
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-vector2.cpp, Page-415

In [1]:
def show(self):
    for i in range(self._vector__size):
        print self.elem(i), ", ",
class vector:
    __v=[int]
    __size=int
    def __init__(self, vector_size):
        if isinstance(vector_size, int):
            self.__size= vector_size
            self.__v=[int]*vector_size
        else:
            print "Copy construcor invoked"
            self.__size=vector_size.__size
            self.__v=[int]*vector_size.__size
            for i in range(vector_size.__size):
                self.__v[i]=vector_size.__v[i]
    def elem(self,i):
        if i>=self.__size:
            print "Error: Out of Range"
            return -1
        return self.__v[i]
    def __del__(self):
        del self.__v
    show=show
v1=vector(5)
v2=vector(5)
for i in range(5):
    if v2.elem(i)!=-1:
        v2._vector__v[i]=i+1
v1=v2
v3=vector(v2)
print "Vector v1: ",
v1.show()
print "\nvector v2: ",
v2.show()
print "\nvector v3: ",
v3.show()
Copy construcor invoked
Vector v1:  1 ,  2 ,  3 ,  4 ,  5 ,  
vector v2:  1 ,  2 ,  3 ,  4 ,  5 ,  
vector v3:  1 ,  2 ,  3 ,  4 ,  5 , 

Example-matrix.cpp, Page-418

In [1]:
TRUE=1
FALSE=0
def __del__(self):
    for i in range(self._matrix__MaxRow):
        del self._matrix__p[i]
    del self._matrix__p
def add(self, a, b):
    self._matrix__MaxRow=a._matrix__MaxRow
    self._matrix__MaxCol=a._matrix__MaxCol
    if (a._matrix__MaxRow!=b._matrix__MaxRow)|(a._matrix__MaxCol!=b._matrix__MaxCol):
        print "Error: invalid matrix order for addition"
        return
    for i in range(self._matrix__MaxRow):
        for j in range(self._matrix__MaxCol):
            self._matrix__p[i][j]=a._matrix__p[i][j]+b._matrix__p[i][j]
def sub(self, a, b):
    self._matrix__MaxRow=a._matrix__MaxRow
    self._matrix__MaxCol=a._matrix__MaxCol
    if (a._matrix__MaxRow!=b._matrix__MaxRow)|(a._matrix__MaxCol!=b._matrix__MaxCol):
        print "Error: invalid matrix order for subtraction"
        return
    for i in range(self._matrix__MaxRow):
        for j in range(self._matrix__MaxCol):
            self._matrix__p[i][j]=a._matrix__p[i][j]-b._matrix__p[i][j]
def mul(self, a, b):
    self._matrix__MaxRow=a._matrix__MaxRow
    self._matrix__MaxCol=a._matrix__MaxCol
    if (a._matrix__MaxCol!=b._matrix__MaxRow):
        print "Error: invalid matrix order for multiplication"
        return
    for i in range(a._matrix__MaxRow):
        for j in range(b._matrix__MaxCol):
            self._matrix__p[i][j]=0
            for k in range(a._matrix__MaxCol):
                self._matrix__p[i][j]+=a._matrix__p[i][j]*b._matrix__p[i][j]
def eql(self, b):
    for i in range(self._matrix__MaxRow):
        for j in range(self._matrix__MaxCol):
            if self._matrix__p[i][i]!=b._matrix__p[i][j]:
                return 0
    return 1
def read(self):
    self._matrix__p = []
    for i in range(self._matrix__MaxRow):
        self._matrix__p.append([])
        for j in range(self._matrix__MaxCol):
            print "Matrix[%d,%d] =? " %(i, j),
            self._matrix__p[i].append(int(raw_input()))
def show(self):
    for i in range(self._matrix__MaxRow):
        for j in range(self._matrix__MaxCol):
            print self._matrix__p[i][j], " ",
        print ""
class matrix:
    __MaxRow=int
    __MaxCol=int
    __p=[int]
    def __init__(self, row=0, col=0):
        self.__MaxRow=row
        self.__MaxCol=col
        if row>0:
            self.__p=[[int]*self.__MaxCol]*self.__MaxRow
    __del__=__del__
    read=read
    show=show
    add=add
    sub=sub
    mul=mul
    eql=eql
print "Enter Matrix A details..."
m=int(raw_input("How many rows? "))
n=int(raw_input("How many columns? "))
a=matrix(m,n)
a.read()
print "Enter Matrix B details..."
p=int(raw_input("How many rows? "))
q=int(raw_input("How many columns? "))
b=matrix(p,q)
b.read()
print "Matrix A is..."
a.show()
print "Matrix B is..."
b.show()
c=matrix(m,n)
c.add(a,b)
print "C=A+B..."
c.show()
d=matrix(m,n)
d.sub(a,b)
print "D=A-B..."
d.show()
e=matrix(m,q)
e.mul(a,b)
print "E=A*B..."
e.show()
print "(Is matrix A equal to matrix B)? ",
if(a.eql(b)):
    print "Yes"
else:
    print "No"
Enter Matrix A details...
How many rows? 3
How many columns? 3
Matrix[0,0] =? 2
 Matrix[0,1] =? 2
 Matrix[0,2] =? 2
 Matrix[1,0] =? 2
 Matrix[1,1] =? 2
 Matrix[1,2] =? 2
 Matrix[2,0] =? 2
 Matrix[2,1] =? 2
 Matrix[2,2] =? 2
 Enter Matrix B details...
How many rows? 3
How many columns? 3
Matrix[0,0] =? 1
 Matrix[0,1] =? 1
 Matrix[0,2] =? 1
 Matrix[1,0] =? 1
 Matrix[1,1] =? 1
 Matrix[1,2] =? 1
 Matrix[2,0] =? 1
 Matrix[2,1] =? 1
 Matrix[2,2] =? 1
 Matrix A is...
2   2   2   
2   2   2   
2   2   2   
Matrix B is...
1   1   1   
1   1   1   
1   1   1   
C=A+B...
3   3   3   
3   3   3   
3   3   3   
D=A-B...
1   1   1   
1   1   1   
1   1   1   
E=A*B...
6   6   6   
6   6   6   
6   6   6   
(Is matrix A equal to matrix B)?  No

Example-person.cpp, Page-423

In [1]:
def __init__(self, NameIn, AddressIn, PhoneIn):
    self._Person__name=NameIn
    self._Person__address=AddressIn
    self._Person__phone=PhoneIn
#inline
def __del__(self):
    del self._Person__name
    del self._Person__address
    del self._Person__phone
def getname(self):
    return self._Person__name
def getaddress(self):
    return self._Person__address
def getphone(self):
    return self._Person__phone
def changename(self, NameIn):
    if(self._Person__name):
        del self._Person__name
    self._Person__name=NameIn
class Person:
    __name=[str]
    __address=[str]
    __phone=[str]
    __init__=__init__
    __del__=__del__
    getname=getname
    getaddress=getaddress
    getphone=getphone
    changename=changename
def printperson(p):
    if(p.getname()):
        print "Name: ", p.getname()
    if(p.getaddress()):
        print "Address: ", p.getaddress()
    if(p.getphone()):
        print "Phone: ", p.getphone()
me=Person("Rajkumar", "E-mail: raj@cdabc.erne.in", "91-080-5584271")
printperson(me)
you=Person("XYZ", "-not sure-", "-not sure-")
print "You XYZ by default..."
printperson(you)
you.changename("ABC")
print "You changed XYZ to ABC..."
printperson(you)
Name:  Rajkumar
Address:  E-mail: raj@cdabc.erne.in
Phone:  91-080-5584271
You XYZ by default...
Name:  XYZ
Address:  -not sure-
Phone:  -not sure-
You changed XYZ to ABC...
Name:  ABC
Address:  -not sure-
Phone:  -not sure-

Example-graph.cpp, Page-425

In [1]:
def __init__(self):
    if(self._Graphics__nobjects[0]==False):
        self._Graphics__setgraphicsmode()
    self._Graphics__nobjects[0]+=1
def __del__(self):
    self._Graphics__nobjects[0]-=1
    if(self._Graphics__nobjects[0]==False):
        self._Graphics__settextmode()
class Graphics:
    __nobjects=[0]
    def __setgraphicsmode(self):
        pass
    def __settextmode(self):
        pass
    __init__=__init__
    __del__=__del__
    def getcount(self):
        return self.__nobjects[0]
def my_func():
    obj=Graphics()
    print "No. of Graphics' objects while in my_func=", obj.getcount()
obj1=Graphics()
print "No. of Graphics' objects before in my_func=", obj1.getcount()
my_func()
print "No. of Graphics' objects after in my_func=", obj1.getcount()
obj2=Graphics()
obj3=Graphics()
obj4=Graphics()
print "Value of static member nobjects after all 3 more objects..."
print "In obj1= ", obj1.getcount()
print "In obj2= ", obj2.getcount()
print "In obj3= ", obj3.getcount()
print "In obj4= ", obj4.getcount()
No. of Graphics' objects before in my_func= 1
No. of Graphics' objects while in my_func= 2
No. of Graphics' objects after in my_func= 1
Value of static member nobjects after all 3 more objects...
In obj1=  4
In obj2=  4
In obj3=  4
In obj4=  4

Example Page-428

In [1]:
def distance(self, a, b):
    self.x=a.x-b.x
    self.y=a.y-b.y
def display(self):
    print "x= ",self.x
    print "y= ", self.y
class point:
    __x=int
    __y=int
    def __init__(self, a=None, b=None):
        if isinstance(a, int):
            self.x=a
            self.y=b
        else:
            self.x=self.y=0
    def __del__(self):
        pass
    distance=distance
    display=display
p1=point(40,18)
p2=point(12,9)
p3=point()
p3.distance(p1,p2)
print "Coordinates of P1: "
p1.display()
print "Coordinates of P2: "
p2.display()
print "distance between P1 and P2: "
p3.display()
Coordinates of P1: 
x=  40
y=  18
Coordinates of P2: 
x=  12
y=  9
distance between P1 and P2: 
x=  28
y=  9

Example Page-430

In [1]:
def display(self):
    print "a =", self.a,
    print "b =", self.b
class data:
    __a=int
    __b=float
    def __init__(self, x=None, y=None):
        if isinstance(x, int):
            self.a=x
            self.b=y
        elif isinstance(x, data):
            self.a=x.a
            self.b=x.b
        else:
            self.a=0
            self.b=0
    display=display
d1=data()
d2=data(12,9.9)
d3=data(d2)
print "For default constructor: "
d1.display()
print"For parameterized constructor: "
d2.display()
print "For Copy Constructor: "
d3.display()
For default constructor: 
a = 0 b = 0
For parameterized constructor: 
a = 12 b = 9.9
For Copy Constructor: 
a = 12 b = 9.9