Chapter 16: Marching Towards C++

Example 16.1, Page number: 537

In [1]:
#Read and display a string

import sys

#Initialize variable
name = raw_input("Enter Your Name : ")

#Result
sys.stdout.write("Your name is %s"%(name))
Enter Your Name : Amit
Your name is Amit

Example 16.2, Page number: 540

In [5]:
#Display the value of a variable using reference variable

import sys

#Variable Initialization
qty = 10
qt = qty
#in python, value tagging method is used for storage. so there is no reference concept

#Result
sys.stdout.write("qty\tqt\n")
sys.stdout.write("%d\t%d\n"%(qty,qt))
qt = qt + 1
qty = qty + 1
sys.stdout.write("%d\t%d\n"%(qty,qt))
qty = qty - 1
qt = qt - 1
sys.stdout.write("%d\t%d\n"%(qty,qt))
qty	qt
10	10
11	11
10	10

Example 16.3, Page number: 541

In [7]:
#Program to use scope access operator.
#Display the variaous values of the same variable declared at different scope levels.

import sys

#Variable Initialization
a = 10

def main():
    a = 20
    sys.stdout.write("::a = %d"%(a))
    return

#There is no scope operator. Intendation is used to define scope/block of statements
main()
sys.stdout.write("    a = %d"%(a))
::a = 20    a = 10

Example 16.4, Page number: 542

In [2]:
#Program to read tow integers through the keyboard.
#Declare the variables in C++ style.

import sys

#Read Variables
num = int(raw_input("Enter Two numbers : "))
num1 = int(raw_input("Enter Two numbers : "))
#No variable declaration is needed in python

#Result
sys.stdout.write("Entered Numbers are : %d  %d"%(num,num1))
                                    
Enter Two numbers : 8
Enter Two numbers : 9
Entered Numbers are : 8  9

Example 16.5, Page number: 543

In [4]:
#Length of a string

import sys

#There is no variable declaration is needed in python
#Read string
name = raw_input("Enter Your Name : ")

#Calculation
len1 = len(name)

#Result
sys.stdout.write("The length of the string is : %d"%(len1))
Enter Your Name : Santosh
The length of the string is : 7

Example 16.6, Page number: 544

In [15]:
#Sum of numbers using function

import sys

#Function definition
def sum1(x,y):
    return x+y
#Forward function definition is not possible in python.
#Otherwise wrap the function within the main() function

#Variable Initialization
a = 20
b = 2.5

#Function call
sys.stdout.write("Sum = %f"%(sum1(a,b)))
Sum = 22.500000

Example 16.7, Page number: 545

In [16]:
#Function with default arguments.

import sys

#Function definition
def sum1(j,k=10,l=15,m=20):
    return j+k+l+m

#Variable Initialization
a = 2
b = 3
c = 4
d = 5

#Result
sys.stdout.write("Sum = %d"%(sum1(a,b,c,d)))
sys.stdout.write("\nSum = %d"%(sum1(a,b,c)))
sys.stdout.write("\nSum = %d"%(sum1(a,b)))
sys.stdout.write("\nSum = %d"%(sum1(a)))
sys.stdout.write("\nSum = %d"%(sum1(b,c,d)))
Sum = 14
Sum = 29
Sum = 40
Sum = 47
Sum = 32

Example 16.8, Page number: 547

In [17]:
#Square of integer and float number using function overloading

import sys

#Function definition/ There is no seperate function definition is needed.
def sqr(s):
    return s*s

#Variable iNitialization
a = 15
b = 2.5

#Result
sys.stdout.write("Square = %d"%(sqr(a)))
sys.stdout.write("\nSquare = %f"%(sqr(b)))
Square = 225
Square = 6.250000

Example 16.9, Page number: 549

In [4]:
#Display private and public member variables of the class.

import sys

#Class declaration
class num:
    def readdata(self,j,k):
        self.x = j
        self.y = k
        
    def display(self):
        sys.stdout.write("x = %d   y = %f"%(self.x,self.y))

#Object declaration
j = num()

#Result
j.z = 'C'
j.readdata(10,10.5)
j.display()
sys.stdout.write("  z = %c"%(j.z))
x = 10   y = 10.500000  z = C

Example 16.10, Page number: 550

In [5]:
#Private and public data member of a class.

import sys

#Class definition
class player:
    def __init__(self,name=None,height=0,weight=0):
        self.name = name
        self.height = height
        self.weight = weight
        
#Object declaration
a = player()

#Variable Initialization
#There is no need/concept for private variables in python.
a.name = "Sanjay"
a.height = 5.5
a.weight = 38

#Result
sys.stdout.write("Height : %d"%(a.height))
sys.stdout.write("\nWeight : %d"%(a.weight))
Height : 5
Weight : 38

Example 16.11, Page number: 551

In [5]:
#Class with member variables and functions. 

import sys

#Class definition
class player:
    def __init__(self,name=None,height=0,weight=0):
        self.name = name
        self.height = height
        self.weight = weight
        
    def setdata(self):
        self.name = raw_input("Enter Name Age Height Weight")
        self.age = int(raw_input("Enter Name Age Height Weight"))
        self.height = float(raw_input("Enter Name Age Height Weight"))
        self.weight = int(raw_input("Enter Name Age Height Weight"))
        
    def show(self):
        sys.stdout.write("\nName    :  %s"%(self.name))
        sys.stdout.write("\nAge     :  %d"%(self.age))
        sys.stdout.write("\nHeight  :  %f"%(self.height))
        sys.stdout.write("\nWeight  :  %d"%(self.weight))
        
#Object declaration
a = player()

#Function call
a.setdata()
a.show()
Enter Name Age Height WeightSanjay
Enter Name Age Height Weight24
Enter Name Age Height Weight5.5
Enter Name Age Height Weight54

Name    :  Sanjay
Age     :  24
Height  :  5.500000
Weight  :  54

Example 16.12, Page number: 552

In [6]:
#Class with member variables and functions.

import sys

#Class definition
class player:
    def __init__(self,name=None,height=0,weight=0):
        self.name = name
        self.height = height
        self.weight = weight
   
    def setdata(self):
        self.name = raw_input("Enter Name Age Height Weight")
        self.age = int(raw_input("Enter Name Age Height Weight"))
        self.height = float(raw_input("Enter Name Age Height Weight"))
        self.weight = int(raw_input("Enter Name Age Height Weight"))
        
    def show(self):
        sys.stdout.write("\nName    :  %s"%(self.name))
        sys.stdout.write("\nAge     :  %d"%(self.age))
        sys.stdout.write("\nHeight  :  %f"%(self.height))
        sys.stdout.write("\nWeight  :  %d"%(self.weight))
#In python, member functions should be defined inside the class instance

#Object declaration
a = player()

#Function call
a.setdata()
a.show()   
Enter Name Age Height WeightAjay
Enter Name Age Height Weight24
Enter Name Age Height Weight5.2
Enter Name Age Height Weight45

Name    :  Ajay
Age     :  24
Height  :  5.200000
Weight  :  45

Example 16.13, Page number: 554

In [1]:
#Static data member. 

import sys

#Class definition
class sumnum:
    def __init__(self,num = 0):
        self.num = num
        
    def input1(self,c):
        self.num = int(raw_input("Enter Number : "))
        c = c + self.num
        return c
        
    def sum1(self,c):
        sys.stdout.write("The sum of entered numbers is %d"%(c))
        
#Object declaration
a = sumnum()
b = sumnum()
c1 = sumnum()
c = 0

#Function call
#There is no static variable in python
c = a.input1(c)
c = b.input1(c)
c = c1.input1(c)

a.sum1(c)
Enter Number : 4
Enter Number : 5
Enter Number : 5
The sum of entered numbers is 14

Example 16.14, Page number: 555

In [11]:
#Static member functions 

import sys

#Class definition
class bita:
    def __initi__(self):
        self.c = 0
    
    @staticmethod    
    def count(c):
        c = c + 1
        return c
    
    @staticmethod
    def display(k,c):
        k = k + 1
        sys.stdout.write("\nCall Number : %d"%(k))
        sys.stdout.write("\nValue of c : %d"%(c))
        return k
        
#Object declaration
b = bita()
c1 = bita()

c = 0
k = 0

#Function call
k = bita.display(k,c)
c = bita.count(c)
c = b.count(c)
c = c1.count(c)
k = bita.display(k,c)
Call Number : 1
Value of c : 0
Call Number : 2
Value of c : 3

Example 16.15, Page number: 557

In [2]:
#Array of objects to maintain records of bank 

import sys

#Class definition
class bank:
    def __init__(self):
        self.city = None
        self.bank = None
        self.branches = 0
        self.no_ac = 0
        
    def input1(self):
        self.city = raw_input("City Name : ")
        self.bank = raw_input("Bank Name : ")
        self.branches = int(raw_input("Total Branches : "))
        self.no_ac = int(raw_input("Number of A/c : "))
        
    def console(self):
        sys.stdout.write("\n\nCity Name    :   %s"%(self.city))
        sys.stdout.write("\nBank Name      :   %s"%(self.bank))
        sys.stdout.write("\nTotal Branches :   %d"%(self.branches))
        sys.stdout.write("\nNumber of A/c  :   %d"%(self.no_ac))
        
#Object declaration
ms = [bank() for i in range(0,2)]

#Processing
for k in range(0,2):
    ms[k].input1()
    
for k in range(0,2):
    ms[k].console()
City Name : Nanded
Bank Name : SNSB
Total Branches : 10
Number of A/c : 7500
City Name : Latur
Bank Name : SNSB
Total Branches : 8
Number of A/c : 5400


City Name    :   Nanded
Bank Name      :   SNSB
Total Branches :   10
Number of A/c  :   7500

City Name    :   Latur
Bank Name      :   SNSB
Total Branches :   8
Number of A/c  :   5400

Example 16.16, Page number: 559

In [3]:
#Accessing private data using non member function

import sys

#Class definition
class ac:
    def __init__(self):
        self.name = None
        self.acno = 0
        self.bal = 0
        
    def read(self):
        self.name = raw_input("Name  : ")
        self.acno = int(raw_input("A/c No  :"))
        self.bal = int(raw_input("Balance : "))
        
#Non member function
def showbal(a):
    sys.stdout.write("\nBalance of A/c no. %d is Rs. %d"%(a.acno,a.bal))
    
#object declaration
k = ac()

#Function call
k.read()
showbal(k)
Name  : Manoj
A/c No  :474
Balance : 40000

Balance of A/c no. 474 is Rs. 40000

Example 16.17, Page number: 561

In [4]:
#Friend function in two classes. 

import sys

#Class definition
class first:
    def __init__(self):
        self.f = 0
        
    def getvalue(self):
        self.f = int(raw_input("Enter a number : "))
        
class second:
    def __init__(self):
        self.s = 0
        
    def getvalue(self):
        self.s = int(raw_input("Enter a number : "))
        
        
#Non member function
def sum1(d,t):
    sys.stdout.write("\nSum of two numbers : %d"%(t.f+d.s))
    
#Object declaration
a = first()
b = second()

#Function call
a.getvalue()
b.getvalue()
sum1(b,a)
Enter a number : 7
Enter a number : 8

Sum of two numbers : 15

Example 16.18, Page number: 562

In [5]:
#String Replacement

import sys

#Class definition
class fandr:
    def __init__(self):
        self.str1 = None
        self.f = ''
        self.r = ''
        
    def accept(self):
        #Since string object does not support item assignment, initialize the string as character array
        self.str1 = ['P','r','o','g','r','a','_','e','r']
        self.f = raw_input("Find what (char) ")
        self.r = raw_input("Replace with (char) ")
        
    def display(self,d):
        sys.stdout.write("%c"%(self.str1[d]))
        
    def len1(self):
        self.l = len(self.str1)
        return self.l
    
    def find(self,i):
        if self.str1[i] == self.f:
            self.replace(i)
            
    def replace(self,k):
        self.str1[k] = self.r
        
#Object declaration
b = fandr()

#function call
b.accept()
l = b.len1()
sys.stdout.write("\nReplaced text : ")

for i in range(0,l):
    b.find(i)
    b.display(i)
Find what (char) _
Replace with (char) m

Replaced text : Programer

Example 16.19, Page number: 564

In [6]:
#Largest out of ten numbers.

import sys

#Class definition
class num:
    def __init__(self):
        self.number = [0 for i in range(0,10)]
        
    def input1(self,i):
        self.number[i] = int(raw_input("Enter Number (%d) : "%(i+1)))
        return self.number[i]
    
    def large(self,s,m):
        if self.number[s] == m:
            sys.stdout.write("\nLargest number : %d"%(self.number[s]))
            return 0
        else:
            return 1
        
#Object declaration
b = num()

sum1 = 0
c = 1

#Sum
for i in range(0,10):
    sum1 = sum1 + b.input1(i)
    
#largest
for k in range(sum1,0,-1):
    for i in range(0,10):
        if c == 1:
            c = b.large(i,k)
        else:
            break
Enter Number (1) : 125
Enter Number (2) : 654
Enter Number (3) : 246
Enter Number (4) : 945
Enter Number (5) : 258
Enter Number (6) : 159
Enter Number (7) : 845
Enter Number (8) : 940
Enter Number (9) : 944
Enter Number (10) : 485

Largest number : 945

Example 16.20, Page number: 567

In [3]:
#Constructor to initialize the class member variables 

import sys

#Class definition
class num:
    #Constructor
    def __init__(self):
        sys.stdout.write("\nConstructor called")
        self.x = 5
        self.a = 0
        self.b = 1
        self.c = 2
        
    def show(self):
        sys.stdout.write("\nx = %d  a = %d  b = %d  c = %d"%(self.x,self.a,self.b,self.c))
        
#Object declaration
x = num()

#Function call
x.show()
Constructor called
x = 5  a = 0  b = 1  c = 2

Example 16.21, Page number: 569

In [4]:
#Constructor with arguments 

import sys

#Class definition
class num:
    #Constructor
    def __init__(self,m,j,k):
        self.a = m
        self.b = j
        self.c = k
        
    def show(self):
        sys.stdout.write("\na = %d  b = %d  c = %d"%(self.a,self.b,self.c))
        
        
#Object declaration
x = num(4,5,7)
y = num(1,2,8)

#Function call
x.show()
y.show()
a = 4  b = 5  c = 7
a = 1  b = 2  c = 8

Example 16.22, Page number: 571

In [1]:
#Constructor overloading

import sys

#Class definition
class num:
    def __init__(self,m = None,j = None,k = None):
        if m and j and k is not None:
            sys.stdout.write("Constructor with three arguments")
            self.a = m
            self.b = j
            self.c = k
        
        else:
            if m and j is not None:
                sys.stdout.write("Constructor with two arguments")
                self.a = m
                self.b = j
                self.c = ''
            else:
                if m == j == k == None:
                    sys.stdout.write("Constructor without arguments")
                    self.a = 0
                    self.b = 0
                    self.c = ''
                    
                    
    def show(self):    
        sys.stdout.write("\na = %d   b = %f c = "%(self.a,self.b))
        print self.c
        
        
#Object declaration

x = num(4,5.5,'A')
x.show()

y = num(1,2.2)
y.show()

z = num()
z.show()
Constructor with three arguments
a = 4   b = 5.500000 c = A
Constructor with two arguments
a = 1   b = 2.200000 c = 
Constructor without arguments
a = 0   b = 0.000000 c = 

Example 16.23, Page number: 573

In [4]:
#Default arguments in constructor. 

import sys

#Class definition
class power:
    def __init__(self,n = 9,p = 3):
        self.num = n
        self.power = p
        self.ans = pow(n,p)
        
    def show(self):
        sys.stdout.write("\n%d raise to %d is %d"%(self.num,self.power,self.ans))
        
        
#Object declaration
p1 = power()
p2 = power(5)

#Result
p1.show()
p2.show()
9 raise to 3 is 729
5 raise to 3 is 125

Example 16.24, Page number: 575

In [11]:
#Object with reference to constructor. 

import sys

#Class definition
class num:
    #There is no overloading concept in python
    def __init__(self,k=None,j=None):
        if k is not None:
            self.n = k
            return
        else:
            if j is not None:
                self.n = j.n
                
    def show(self):
        sys.stdout.write("%d"%(self.n))
        
#Object creation
J = num(50)
K = num(J.n)
L = num()
L = J
M = num()
M = J

#Result
sys.stdout.write("\nObject J Value of n : ")
J.show()
sys.stdout.write("\nObject K Value of n : ")
K.show()
sys.stdout.write("\nObject L Value of n : ")
L.show()
sys.stdout.write("\nObject M Value of n : ")
M.show()
Object J Value of n : 50
Object K Value of n : 50
Object L Value of n : 50
Object M Value of n : 50

Example 16.25, Page number: 576

In [15]:
#Destructors

import sys

c = 0

#Class definition
class num:
    def __init__(self,c):
        c = c + 1
        sys.stdout.write("\nObject Created : Object(%d)"%(c))
        
        
    def __exit__(self, type, value, traceback,c):
        self.package_obj.cleanup()
        sys.stdout.write("\nObject Released : Object(%d)"%(c))
        c = c - 1
       
        
#Object creation
sys.stdout.write("\nIn main()\n")
a = num(c)
b = num(c)

sys.stdout.write("\nIn Block A()\n")
c = num(c)

sys.stdout.write("\n\nAgain in main()\n")
In main()

Object Created : Object(1)
Object Created : Object(1)
In Block A()

Object Created : Object(1)

Again in main()

Example 16.26, Page number: 579

In [7]:
#Overload unary ++ operator

import sys

#Class definition
class num:
    def input1(self):
        self.a = int(raw_input("Enter Values for a,b,c and d : "))
        self.b = int(raw_input("Enter Values for a,b,c and d : "))
        self.c = int(raw_input("Enter Values for a,b,c and d : "))
        self.d = int(raw_input("Enter Values for a,b,c and d : "))
        
    def show(self):
        sys.stdout.write("\nA = %d  B = %d  C = %d  D = %d"%(self.a,self.b,self.c,self.d))
        
    def operatorplusplus(self):
        self.a = self.a + 1
        self.b = self.b + 1
        self.c = self.c + 1
        self.d = self.d + 1
        
#Object creation
X = num()

X.input1()
sys.stdout.write("\nBefore Overloading X  : ")
X.show()

#There is no operator overloading in python
X.operatorplusplus()
sys.stdout.write("\nAfter Overloading X  : ")
X.show()
Enter Values for a,b,c and d : 4
Enter Values for a,b,c and d : 5
Enter Values for a,b,c and d : 8
Enter Values for a,b,c and d : 9

Before Overloading X  : 
A = 4  B = 5  C = 8  D = 9
After Overloading X  : 
A = 5  B = 6  C = 9  D = 10

Example 16.27, Page number: 581

In [8]:
#Overload + binary operator

import sys

#Class definition
class num:
    def input1(self):
        self.a = int(raw_input("Enter Values for a,b,c and d : "))
        self.b = int(raw_input("Enter Values for a,b,c and d : "))
        self.c = int(raw_input("Enter Values for a,b,c and d : "))
        self.d = int(raw_input("Enter Values for a,b,c and d : "))
        
    def show(self):
        sys.stdout.write("A = %d  B = %d  C = %d  D = %d"%(self.a,self.b,self.c,self.d))
        
    def operatorplus(self,t):
        tmp = num()
        tmp.a = self.a + t.a
        tmp.b = self.b + t.b
        tmp.c = self.c + t.c
        tmp.d = self.d + t.d
        return tmp
    
#Object creation
X = num()
Y = num()
Z = num()

#Result
sys.stdout.write("\nObject X ")
X.input1()
sys.stdout.write("\nObject Y ")
Y.input1()

Z = X.operatorplus(Y)

sys.stdout.write("\nX : ")
X.show()
sys.stdout.write("\nY : ")
Y.show()
sys.stdout.write("\nZ : ")
Z.show()
Object X Enter Values for a,b,c and d : 1
Enter Values for a,b,c and d : 4
Enter Values for a,b,c and d : 2
Enter Values for a,b,c and d : 1

Object Y Enter Values for a,b,c and d : 2
Enter Values for a,b,c and d : 5
Enter Values for a,b,c and d : 4
Enter Values for a,b,c and d : 2

X : A = 1  B = 4  C = 2  D = 1
Y : A = 2  B = 5  C = 4  D = 2
Z : A = 3  B = 9  C = 6  D = 3

Example 16.28, Page number: 583

In [9]:
#Multiplication using an integer and object. 

import sys

#Class definition
class num:
    def input1(self):
        self.a = int(raw_input("Enter Values for a,b,c and d : "))
        self.b = int(raw_input("Enter Values for a,b,c and d : "))
        self.c = int(raw_input("Enter Values for a,b,c and d : "))
        self.d = int(raw_input("Enter Values for a,b,c and d : "))
        
    def show(self):
        sys.stdout.write("A = %d  B = %d  C = %d  D = %d"%(self.a,self.b,self.c,self.d))
        
def operatormul(a,t):
    tmp = num()
    tmp.a = a * t.a
    tmp.b = a * t.b
    tmp.c = a * t.c
    tmp.d = a * t.d
    return tmp

#Result
X = num()
Z = num()

sys.stdout.write("\nObject X ")
X.input1()

Z = operatormul(3,X)
sys.stdout.write("\nX : ")
X.show()
sys.stdout.write("\nZ : ")
Z.show()
Object X Enter Values for a,b,c and d : 1
Enter Values for a,b,c and d : 2
Enter Values for a,b,c and d : 2
Enter Values for a,b,c and d : 3

X : A = 1  B = 2  C = 2  D = 3
Z : A = 3  B = 6  C = 6  D = 9

Example 16.29, Page number: 585

In [10]:
#Inheritance

import sys

#Class declaration
class one:
    def __init__(self):
        self.a = 0
        self.b = 0
        
class two(one):
    def __init__(self):
        one.__init__(self)
        self.c = 0
        self.d = 0
        
    def input1(self):
        self.a = int(raw_input("Enter values for a,b,c,d : "))
        self.b = int(raw_input("Enter values for a,b,c,d : "))
        self.c = int(raw_input("Enter values for a,b,c,d : "))
        self.d = int(raw_input("Enter values for a,b,c,d : "))
        
    def display(self):
        sys.stdout.write("\na = %d  b = %d  c = %d  d = %d"%(self.a,self.b,self.c,self.d))
        
#Object declaration
a = two()

#Result
a.input1()
a.display()
        
Enter values for a,b,c,d : 2
Enter values for a,b,c,d : 5
Enter values for a,b,c,d : 4
Enter values for a,b,c,d : 7

a = 2  b = 5  c = 4  d = 7

Example 16.30, Page number: 586

In [4]:
#Member function using pointer

import sys

#class declaration
class super1:
    def display(self):
        sys.stdout.write("\nIn function display()  class super")
        
    def show(self):
        sys.stdout.write("\nIn function show() class super")
        
class sub(super1):
    def display(self):
        sys.stdout.write("\nIn function display() class sub")
        
    def show(self):
        sys.stdout.write("\nIn function show() class sub")
        
#Object declaration
S = super1()
A = sub()

#There is no pointer concept in python
S.display()
S.show()

sys.stdout.write("\n\nNow Pointer point points to derived class sub\n")
A.display()
A.show()
In function display()  class super
In function show() class super

Now Pointer point points to derived class sub

In function display() class sub
In function show() class sub
In [ ]: