Chapter 12-Dynamic Objects

Example-ptrobj1.cpp, Page no-435

In [2]:
from ctypes import Structure, POINTER
class someclass(Structure):
    data1=int
    data2=chr
    def __init__(self):
        print 'Constructor someclass() is invoked'
        self.data1=1
        self.data2='A'
    def __del__(self):
        print 'Destructor ~someclass() is invoked'
    def show(self):
        print 'data1 =', self.data1,
        print 'data2 =', self.data2
object1=someclass() #object of class someclass
ptr=POINTER(someclass) #pointer of type class someclass
ptr=object1 #pointer pointing to object of class someclass
print "Accessing object through object1.show()..."
object1.show()
print "Accessing object through ptr->show()..."
ptr.show()
Constructor someclass() is invoked
Destructor ~someclass() is invoked
Accessing object through object1.show()...
data1 = 1 data2 = A
Accessing object through ptr->show()...
data1 = 1 data2 = A

Example-ptrobj2.cpp, Page no-437

In [3]:
class someclass(Structure):
    data1=int
    data2=chr
    def __init__(self):
        print 'Constructor someclass() is invoked'
        self.data1=1
        self.data2='A'
    def __del__(self):
        print 'Destructor ~someclass() is invoked'
    def show(self):
        print 'data1 =', self.data1,
        print 'data2 =', self.data2
object1=someclass()
ptr=POINTER(someclass)
ptr=object1
print "Accessing object through object1.show()..."
ptr.show()
print "Destroying dynamic object..."
del ptr
Constructor someclass() is invoked
Destructor ~someclass() is invoked
Accessing object through object1.show()...
data1 = 1 data2 = A
Destroying dynamic object...

Example-useref.cpp, Page no-439

In [1]:
from ctypes import POINTER, c_int
t1=POINTER(c_int)
t1=c_int(5)
t3=c_int(5)
t2=c_int(10)
t1.value=t1.value+t2.value
print "Sum of", t3.value,
print "and", t2.value, 
print "is:", t1.value
Sum of 5 and 10 is: 15

Example-refobj.cpp, Page no-440

In [1]:
from ctypes import Structure
class student(Structure):
    __roll_no=int
    __name=str
    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()
s1.setdata(1, "Savithri")
s1.outdata()
s2=student()
s2.setdata(2, "Bhavani")
s2.outdata()
s3=student()
s3.setdata(3, "Vani")
s4=s3
s3.outdata()
s4.outdata()
Roll No = 1
Name = Savithri
Roll No = 2
Name = Bhavani
Roll No = 3
Name = Vani
Roll No = 3
Name = Vani

Example-student3.cpp, Page no-442

In [3]:
class student:
    __roll_no=int
    __name=str
    def __init__(self, roll_no_in=None, name_in=None):
        if isinstance(roll_no_in, int):
            self.__roll_no=roll_no_in
            if isinstance(name_in, str):
                self.__name=name_in
        else:
            flag=raw_input("Do you want to initialize the object (y/n): ")
            if flag=='y' or flag=='Y':
                self.__roll_no=int(raw_input("Enter Roll no. of student: "))
                Str=raw_input("Enter Name of student: ")
                self.__name=Str
            else:
                self.__roll_no=0
                self.__name=None
    def __del__(self):
        if isinstance(self.__name, str):
            del self.__name
    def Set(self):
        student(roll_no_in, name_in)
    def show(self):
        if self.__roll_no:
            print "Roll No:", self.__roll_no
        else:
            print "Roll No: (not initialized)"
        if isinstance(self.__name, str):
            print "Name: ", self.__name
        else:
            print "Name: (not initialized)"
s1=student()
s2=student()
s3=student(1)
s4=student(2, "Bhavani")
print "Live objects contents..."
s1.show()
s2.show()
s3.show()
s4.show()
del s1
del s2
del s3
del s4
Do you want to initialize the object (y/n): n
Do you want to initialize the object (y/n): y
Enter Roll no. of student: 5
Enter Name of student: Rekha
Live objects contents...
Roll No: (not initialized)
Name: (not initialized)
Roll No: 5
Name:  Rekha
Roll No: 1
Name: (not initialized)
Roll No: 2
Name:  Bhavani

Example-student1.cpp, Page-445

In [4]:
class student:
    __roll_no=int
    __name=str
    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
s=[]*10 #array of objects
count=0
for i in range(10):
    s.append(student())
for i in range(10):
    response=raw_input("Initialize student object (y/n): ")
    if response=='y' or response=='Y':
        roll_no=int(raw_input("Enter a Roll no. of student: "))
        name=raw_input("Enter name of student: ")
        s[i].setdata(roll_no, name)
        count+=1
    else:
        break
print "Student Details..."
for i in range(count):
    s[i].outdata()
Initialize student object (y/n): y
Enter a Roll no. of student: 1
Enter name of student: Rajkumar
Initialize student object (y/n): y
Enter a Roll no. of student: 2
Enter name of student: Tejaswi
Initialize student object (y/n): y
Enter a Roll no. of student: 3
Enter name of student: Savithri
Initialize student object (y/n): n
Student Details...
Roll No = 1
Name = Rajkumar
Roll No = 2
Name = Tejaswi
Roll No = 3
Name = Savithri

Example-student2.cpp, Page no-447

In [6]:
class student(Structure):
    __roll_no=int
    __name=str
    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
temp=[]*10
s=POINTER(student) 
count=0
for i in range(10):
    temp.append(student())
s=temp #pointer to array of objects
for i in range(10):
    response=raw_input("Create student object (y/n): ")
    if response=='y' or response=='Y':
        roll_no=int(raw_input("Enter a Roll no. of student: "))
        name=raw_input("Enter name of student: ")
        s[i].setdata(roll_no, name)
        count+=1
    else:
        break
print "Student Details..."
for i in range(count):
    s[i].outdata()
Create student object (y/n): y
Enter a Roll no. of student: 1
Enter name of student: Rajkumar
Create student object (y/n): y
Enter a Roll no. of student: 2
Enter name of student: Tejaswi
Create student object (y/n): y
Enter a Roll no. of student: 3
Enter name of student: Savithri
Create student object (y/n): n
Student Details...
Roll No = 1
Name = Rajkumar
Roll No = 2
Name = Tejaswi
Roll No = 3
Name = Savithri

Example-ptrmemb.cpp, Page no-452

In [1]:
class X:
    __y=int
    a=int
    b=int
    def init(self, z):
        self.a=z
        return z
obj=X()
ip=X.a #pointer to data member
obj.ip=10 #access through object
print "a in obj after obj.*ip = 10 is", obj.ip
pobj=[obj] #pointer to object of class X
pobj[0].ip=10 #access through object pointer
print "a in obj after pobj->*ip = 10 is", pobj[0].ip
ptr_init=X.init #pointer to member function
ptr_init(obj,5) #access through object
print "a in obj after (obj.*ptr_init)(5) =", obj.a
ptr_init(pobj[0],5) #access through object pointer
print "a in obj after (pobj->*ptr_init)(5) =", obj.a
a in obj after obj.*ip = 10 is 10
a in obj after pobj->*ip = 10 is 10
a in obj after (obj.*ptr_init)(5) = 5
a in obj after (pobj->*ptr_init)(5) = 5

Example-friend.cpp, Page no-454

In [1]:
class X():
    __a=int
    __b=int
    def __init__(self):
        self.__a=0
        self.__b=0
    def SetMembers(self, a1, b1):
        self.__a=a1
        self.__b=b1
def sum(objx):
    pa=[X._X__a]
    pb=[X._X__b]
    objx.pa=objx._X__a
    objx.pb=objx._X__b
    return objx.pa+objx.pb
objx=X()
pfunc=X.SetMembers
pfunc(objx, 5, 6)
print "Sum =", sum(objx)
pobjx=[objx]
pfunc(pobjx[0], 7, 8)
print "Sum =", sum(objx)
Sum = 11
Sum = 15

Example-memhnd.cpp, Page no-455

In [1]:
from ctypes import pointer, c_int
def out_of_memory():
    print "Memory exhausted, cannot allocate"
ip=pointer(c_int())
total_allocated=0L
print "Ok, allocating..."
while(1):
    ip=[int]*100
    total_allocated+=100L
    print "Now got a total of", total_allocated, "bytes"
    if total_allocated==29900L:
        break
Ok, allocating...
Now got a total of 100 bytes
Now got a total of 200 bytes
Now got a total of 300 bytes
Now got a total of 400 bytes
Now got a total of 500 bytes
Now got a total of 600 bytes
Now got a total of 700 bytes
Now got a total of 800 bytes
Now got a total of 900 bytes
Now got a total of 1000 bytes
Now got a total of 1100 bytes
Now got a total of 1200 bytes
Now got a total of 1300 bytes
Now got a total of 1400 bytes
Now got a total of 1500 bytes
Now got a total of 1600 bytes
Now got a total of 1700 bytes
Now got a total of 1800 bytes
Now got a total of 1900 bytes
Now got a total of 2000 bytes
Now got a total of 2100 bytes
Now got a total of 2200 bytes
Now got a total of 2300 bytes
Now got a total of 2400 bytes
Now got a total of 2500 bytes
Now got a total of 2600 bytes
Now got a total of 2700 bytes
Now got a total of 2800 bytes
Now got a total of 2900 bytes
Now got a total of 3000 bytes
Now got a total of 3100 bytes
Now got a total of 3200 bytes
Now got a total of 3300 bytes
Now got a total of 3400 bytes
Now got a total of 3500 bytes
Now got a total of 3600 bytes
Now got a total of 3700 bytes
Now got a total of 3800 bytes
Now got a total of 3900 bytes
Now got a total of 4000 bytes
Now got a total of 4100 bytes
Now got a total of 4200 bytes
Now got a total of 4300 bytes
Now got a total of 4400 bytes
Now got a total of 4500 bytes
Now got a total of 4600 bytes
Now got a total of 4700 bytes
Now got a total of 4800 bytes
Now got a total of 4900 bytes
Now got a total of 5000 bytes
Now got a total of 5100 bytes
Now got a total of 5200 bytes
Now got a total of 5300 bytes
Now got a total of 5400 bytes
Now got a total of 5500 bytes
Now got a total of 5600 bytes
Now got a total of 5700 bytes
Now got a total of 5800 bytes
Now got a total of 5900 bytes
Now got a total of 6000 bytes
Now got a total of 6100 bytes
Now got a total of 6200 bytes
Now got a total of 6300 bytes
Now got a total of 6400 bytes
Now got a total of 6500 bytes
Now got a total of 6600 bytes
Now got a total of 6700 bytes
Now got a total of 6800 bytes
Now got a total of 6900 bytes
Now got a total of 7000 bytes
Now got a total of 7100 bytes
Now got a total of 7200 bytes
Now got a total of 7300 bytes
Now got a total of 7400 bytes
Now got a total of 7500 bytes
Now got a total of 7600 bytes
Now got a total of 7700 bytes
Now got a total of 7800 bytes
Now got a total of 7900 bytes
Now got a total of 8000 bytes
Now got a total of 8100 bytes
Now got a total of 8200 bytes
Now got a total of 8300 bytes
Now got a total of 8400 bytes
Now got a total of 8500 bytes
Now got a total of 8600 bytes
Now got a total of 8700 bytes
Now got a total of 8800 bytes
Now got a total of 8900 bytes
Now got a total of 9000 bytes
Now got a total of 9100 bytes
Now got a total of 9200 bytes
Now got a total of 9300 bytes
Now got a total of 9400 bytes
Now got a total of 9500 bytes
Now got a total of 9600 bytes
Now got a total of 9700 bytes
Now got a total of 9800 bytes
Now got a total of 9900 bytes
Now got a total of 10000 bytes
Now got a total of 10100 bytes
Now got a total of 10200 bytes
Now got a total of 10300 bytes
Now got a total of 10400 bytes
Now got a total of 10500 bytes
Now got a total of 10600 bytes
Now got a total of 10700 bytes
Now got a total of 10800 bytes
Now got a total of 10900 bytes
Now got a total of 11000 bytes
Now got a total of 11100 bytes
Now got a total of 11200 bytes
Now got a total of 11300 bytes
Now got a total of 11400 bytes
Now got a total of 11500 bytes
Now got a total of 11600 bytes
Now got a total of 11700 bytes
Now got a total of 11800 bytes
Now got a total of 11900 bytes
Now got a total of 12000 bytes
Now got a total of 12100 bytes
Now got a total of 12200 bytes
Now got a total of 12300 bytes
Now got a total of 12400 bytes
Now got a total of 12500 bytes
Now got a total of 12600 bytes
Now got a total of 12700 bytes
Now got a total of 12800 bytes
Now got a total of 12900 bytes
Now got a total of 13000 bytes
Now got a total of 13100 bytes
Now got a total of 13200 bytes
Now got a total of 13300 bytes
Now got a total of 13400 bytes
Now got a total of 13500 bytes
Now got a total of 13600 bytes
Now got a total of 13700 bytes
Now got a total of 13800 bytes
Now got a total of 13900 bytes
Now got a total of 14000 bytes
Now got a total of 14100 bytes
Now got a total of 14200 bytes
Now got a total of 14300 bytes
Now got a total of 14400 bytes
Now got a total of 14500 bytes
Now got a total of 14600 bytes
Now got a total of 14700 bytes
Now got a total of 14800 bytes
Now got a total of 14900 bytes
Now got a total of 15000 bytes
Now got a total of 15100 bytes
Now got a total of 15200 bytes
Now got a total of 15300 bytes
Now got a total of 15400 bytes
Now got a total of 15500 bytes
Now got a total of 15600 bytes
Now got a total of 15700 bytes
Now got a total of 15800 bytes
Now got a total of 15900 bytes
Now got a total of 16000 bytes
Now got a total of 16100 bytes
Now got a total of 16200 bytes
Now got a total of 16300 bytes
Now got a total of 16400 bytes
Now got a total of 16500 bytes
Now got a total of 16600 bytes
Now got a total of 16700 bytes
Now got a total of 16800 bytes
Now got a total of 16900 bytes
Now got a total of 17000 bytes
Now got a total of 17100 bytes
Now got a total of 17200 bytes
Now got a total of 17300 bytes
Now got a total of 17400 bytes
Now got a total of 17500 bytes
Now got a total of 17600 bytes
Now got a total of 17700 bytes
Now got a total of 17800 bytes
Now got a total of 17900 bytes
Now got a total of 18000 bytes
Now got a total of 18100 bytes
Now got a total of 18200 bytes
Now got a total of 18300 bytes
Now got a total of 18400 bytes
Now got a total of 18500 bytes
Now got a total of 18600 bytes
Now got a total of 18700 bytes
Now got a total of 18800 bytes
Now got a total of 18900 bytes
Now got a total of 19000 bytes
Now got a total of 19100 bytes
Now got a total of 19200 bytes
Now got a total of 19300 bytes
Now got a total of 19400 bytes
Now got a total of 19500 bytes
Now got a total of 19600 bytes
Now got a total of 19700 bytes
Now got a total of 19800 bytes
Now got a total of 19900 bytes
Now got a total of 20000 bytes
Now got a total of 20100 bytes
Now got a total of 20200 bytes
Now got a total of 20300 bytes
Now got a total of 20400 bytes
Now got a total of 20500 bytes
Now got a total of 20600 bytes
Now got a total of 20700 bytes
Now got a total of 20800 bytes
Now got a total of 20900 bytes
Now got a total of 21000 bytes
Now got a total of 21100 bytes
Now got a total of 21200 bytes
Now got a total of 21300 bytes
Now got a total of 21400 bytes
Now got a total of 21500 bytes
Now got a total of 21600 bytes
Now got a total of 21700 bytes
Now got a total of 21800 bytes
Now got a total of 21900 bytes
Now got a total of 22000 bytes
Now got a total of 22100 bytes
Now got a total of 22200 bytes
Now got a total of 22300 bytes
Now got a total of 22400 bytes
Now got a total of 22500 bytes
Now got a total of 22600 bytes
Now got a total of 22700 bytes
Now got a total of 22800 bytes
Now got a total of 22900 bytes
Now got a total of 23000 bytes
Now got a total of 23100 bytes
Now got a total of 23200 bytes
Now got a total of 23300 bytes
Now got a total of 23400 bytes
Now got a total of 23500 bytes
Now got a total of 23600 bytes
Now got a total of 23700 bytes
Now got a total of 23800 bytes
Now got a total of 23900 bytes
Now got a total of 24000 bytes
Now got a total of 24100 bytes
Now got a total of 24200 bytes
Now got a total of 24300 bytes
Now got a total of 24400 bytes
Now got a total of 24500 bytes
Now got a total of 24600 bytes
Now got a total of 24700 bytes
Now got a total of 24800 bytes
Now got a total of 24900 bytes
Now got a total of 25000 bytes
Now got a total of 25100 bytes
Now got a total of 25200 bytes
Now got a total of 25300 bytes
Now got a total of 25400 bytes
Now got a total of 25500 bytes
Now got a total of 25600 bytes
Now got a total of 25700 bytes
Now got a total of 25800 bytes
Now got a total of 25900 bytes
Now got a total of 26000 bytes
Now got a total of 26100 bytes
Now got a total of 26200 bytes
Now got a total of 26300 bytes
Now got a total of 26400 bytes
Now got a total of 26500 bytes
Now got a total of 26600 bytes
Now got a total of 26700 bytes
Now got a total of 26800 bytes
Now got a total of 26900 bytes
Now got a total of 27000 bytes
Now got a total of 27100 bytes
Now got a total of 27200 bytes
Now got a total of 27300 bytes
Now got a total of 27400 bytes
Now got a total of 27500 bytes
Now got a total of 27600 bytes
Now got a total of 27700 bytes
Now got a total of 27800 bytes
Now got a total of 27900 bytes
Now got a total of 28000 bytes
Now got a total of 28100 bytes
Now got a total of 28200 bytes
Now got a total of 28300 bytes
Now got a total of 28400 bytes
Now got a total of 28500 bytes
Now got a total of 28600 bytes
Now got a total of 28700 bytes
Now got a total of 28800 bytes
Now got a total of 28900 bytes
Now got a total of 29000 bytes
Now got a total of 29100 bytes
Now got a total of 29200 bytes
Now got a total of 29300 bytes
Now got a total of 29400 bytes
Now got a total of 29500 bytes
Now got a total of 29600 bytes
Now got a total of 29700 bytes
Now got a total of 29800 bytes
Now got a total of 29900 bytes

Example-this.cpp, Page no-457

In [1]:
class Test:
    __a=int
    def setdata(self, init_a):
        self.__a=init_a
        print "Address of my object, this in setdata():", hex(id(self))
        self.__a=init_a
    def showdata(self):
        print "Data accessed in normal way: ", self.__a
        print "Address of my object, this in showdata(): ", hex(id(self))
        print "Data accessed through this->a: ", self.__a
my=Test()
my.setdata(25)
my.showdata()
Address of my object, this in setdata(): 0x39de488L
Data accessed in normal way:  25
Address of my object, this in showdata():  0x39de488L
Data accessed through this->a:  25

Example-list.cpp, Page no-459

In [1]:
class List():
    def __init__(self, dat=None):
        if isinstance(dat, int):
            self.__data=dat
        else:
            self.__data=0
        self.__Next=None
    def __del__(self):
        pass
    def get(self):
        return self.__data
    def insert(self, node):
        last=List()
        last=self
        while(last.__Next!=None):
            last=last.__Next
        last.__Next=node
def display(first):
    traverse=List()
    print "List traversal yields:",
    traverse=first
    while(1):        
        print traverse._List__data, ",",
        if traverse._List__Next==None:
            break
        traverse=traverse._List__Next
    print ""
first=List()
first=None
while(1):
    print "Linked List...\n1.Insert\n2.Display\n3.Quit\nEnter Choice: ",
    choice=int(raw_input())
    if choice==1:
        data=int(raw_input("Enter data: "))
        node=List(data)
        if first==None:
            first=node
        else:
            first.insert(node)
    elif choice==2:
        display(first)
    elif choice==3:
        break
    else:
        print "Bad Option Selected"
Linked List...
1.Insert
2.Display
3.Quit
Enter Choice: 1
Enter data: 2
 Linked List...
1.Insert
2.Display
3.Quit
Enter Choice: 2
 List traversal yields: 2 , 
Linked List...
1.Insert
2.Display
3.Quit
Enter Choice: 1
Enter data: 3
 Linked List...
1.Insert
2.Display
3.Quit
Enter Choice: 1
Enter data: 4
 Linked List...
1.Insert
2.Display
3.Quit
Enter Choice: 2
 List traversal yields: 2 , 3 , 4 , 
Linked List...
1.Insert
2.Display
3.Quit
Enter Choice: 3

Example-dll.cpp, Page no-462

In [1]:
class dll:
    def __init__(self, data_in=None):
        if isinstance(data_in, int):
            self.__data=data_in
        else:
            self.__data=0
        self.__prev=None
        self.__Next=None
    def __del__(self):
        pass
    def get(self):
        return self.__data
    def insert(self, node):
        last=dll()
        last=self
        while(last._dll__Next!=None):
            last=last._dll__Next
        node._dll__prev=last
        node._dll__Next=None
        last._dll__Next=node
    def FreeAllNodes(self):
        print "Freeing the node with data:",
        first=dll()
        first=self
        while(1):
            temp= dll()
            temp=first
            print "->", first._dll__data,
            del temp
            first=first._dll__Next
            if first==None:
                break
def display(first):
    traverse=dll()
    traverse=first
    if first==None:
        print "Nothing to display !"
        return
    else:
        print "Processing with forward -> pointer:",
        while(1):        
            print "->", traverse._dll__data, 
            if traverse._dll__Next==None:
                break
            traverse=traverse._dll__Next
        print "\nProcessing with backward <- pointer:",
        while(1):        
            print "->", traverse._dll__data,
            if traverse._dll__prev==None:
                break
            traverse=traverse._dll__prev
        print ""
def InsertNode(first, data):
    node=dll(data)
    if first==None:
        first=node
    else:
        first.insert(node)
    return first
first=dll()
first=None
print "Double Linked List Manipulation..."
while(1):
    choice=int(raw_input("Enter Choice ([1] Insert, [2] Display, [3]Quit: "))
    if choice==1:
        data=int(raw_input("Enter data: "))
        first=InsertNode(first, data)
    elif choice==2:
        display(first)
    elif choice==3:
        first.FreeAllNodes()
        break
    else:
        print "Bad Option Selected"
Double Linked List Manipulation...
Enter Choice ([1] Insert, [2] Display, [3]Quit: 1
Enter data: 3
Enter Choice ([1] Insert, [2] Display, [3]Quit: 2
Processing with forward -> pointer: -> 3 
Processing with backward <- pointer: -> 3 
Enter Choice ([1] Insert, [2] Display, [3]Quit: 1
Enter data: 7
Enter Choice ([1] Insert, [2] Display, [3]Quit: 2
Processing with forward -> pointer: -> 3 -> 7 
Processing with backward <- pointer: -> 7 -> 3 
Enter Choice ([1] Insert, [2] Display, [3]Quit: 1
Enter data: 5
Enter Choice ([1] Insert, [2] Display, [3]Quit: 2
Processing with forward -> pointer: -> 3 -> 7 -> 5 
Processing with backward <- pointer: -> 5 -> 7 -> 3 
Enter Choice ([1] Insert, [2] Display, [3]Quit: 0
Bad Option Selected
Enter Choice ([1] Insert, [2] Display, [3]Quit: 3
Freeing the node with data: -> 3 -> 7 -> 5

Example-1, Page no-466

In [1]:
class A:
    __a1=int
    def Set(self, val):
        self.__a1=val
class B:
    __b1=int
    def Set(self, val):
        self.__b1=val
def add(x, y):
    return x._A__a1+y._B__b1
ObjA=A()
ObjB=B()
ObjA.Set(9)
ObjB.Set(10)
print "Sum of objects A and B using friend function =", add(ObjA, ObjB)
Sum of objects A and B using friend function = 19

Example-2, Page no-466

In [1]:
class test:
    __data=int
    def func(self, val):
        self.__data=val
t1=test()
testptr={}
testptr[0]=test.func #pointer to member function
print "Initializing test class object t1 using pointer..."
testptr[0](t1, 10)
print "Object initialized successfully"
Initializing test class object t1 using pointer...
Object initialized successfully