Chapter 20: Namespaces and Other Advanced Topics

Example 20.1, Page Number:474

In [1]:
class CounterNameSpace:
    upperbound=None
    lowerbound=None
    class counter:
        def __init__(self,n):
            if n<=CounterNameSpace.upperbound:
                self.count=n
            else:
                self.count=CounterNameSpace.upperbound
        def reset(self,n):
            if n<=CounterNameSpace.upperbound:
                self.count=n
        def run(self):
            if self.count>CounterNameSpace.lowerbound:
                self.count-=1
                return self.count
            else:
                return CounterNameSpace.lowerbound
            
CounterNameSpace.upperbound=100
CounterNameSpace.lowerbound=0


ob1=CounterNameSpace.counter(10)
while True:
    i=ob1.run()
    print i,
    if i<=CounterNameSpace.lowerbound:
        break        
print


ob2=CounterNameSpace.counter(20)
while True:
    i=ob2.run()
    print i,
    if i<=CounterNameSpace.lowerbound:
        break   
print


ob2.reset(100)
CounterNameSpace.lowerbound=90
while True:
    i=ob2.run()
    print i,
    if i<=CounterNameSpace.lowerbound:
        break   
9 8 7 6 5 4 3 2 1 0
19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
99 98 97 96 95 94 93 92 91 90

Example 20.2, Page Number:476

In [2]:
 
class CounterNameSpace:
    upperbound=None
    lowerbound=None
    class counter:
        def __init__(self,n):
            if n<=c.upperbound:
                self.count=n
            else:
                self.count=c.upperbound
        def reset(self,n):
            if n<=c.upperbound:
                self.count=n
        def run(self):
            if self.count>c.lowerbound:
                self.count-=1
                return self.count
            else:
                return c.lowerbound

#Use only upperbound using c
c=CounterNameSpace()
c.upperbound=100
CounterNameSpace.lowerbound=0


ob1=CounterNameSpace.counter(10)
while True:
    i=ob1.run()
    print i,
    if i<=CounterNameSpace.lowerbound:
        break        
print

#Now use entre CounterName Space using c

ob2=c.counter(20)
while True:
    i=ob2.run()
    print i,
    if i<=c.lowerbound:
        break   
print


ob2.reset(100)
c.lowerbound=90
while True:
    i=ob2.run()
    print i,
    if i<=c.lowerbound:
        break   
9 8 7 6 5 4 3 2 1 0
19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
99 98 97 96 95 94 93 92 91 90

Example 20.3, Page Number:479

In [3]:
#User-input
print "Enter a number:"
val= 10.00

#Result
print "This is your number:",val
Enter a number:
This is your number: 10.0

Example 20.4, Page Number:479

In [5]:
import sys

#User-input
sys.stdout.write("Enter a number:")
val= 10.00

#Result
sys.stdout.write("\nThis is your number: ")
sys.stdout.write(str(val))
Enter a number:
This is your number: 10.0

Example 20.5, Page Number:479

In [6]:
from sys import stdout

#User-input
stdout.write("Enter a number:")
val= 10.00

#Result
stdout.write("\nThis is your number: ")
stdout.write(str(val))
Enter a number:
This is your number: 10.0

Example 20.6, Page Number:480

In [7]:
 
def vline(i):
    for j in xrange(i,0,-1):
        print "|"
def hline(i):
    for j in xrange(i,0,-1):
        print "-",
    print 

p=vline      #p points to vline
p(4)         #call vline()

p=hline      #p now points to hline
p(3)         #call hline
|
|
|
|
- - -

Example 20.7, Page Number:482

In [8]:
import string

def qsort(p):
    if p == []: 
        return []
    else:
        pivot = p[0]
        lesser = qsort([x for x in p[1:] if x < pivot])
        greater = qsort([x for x in p[1:] if x >= pivot])
        return lesser + [pivot] + greater
 
#Variable Declaration        
str="Function pointers provide flexibility." 

#sorting the string
str=qsort(str)
str=string.join(str)

#Result
print "sorted strng: ",str
sorted strng:        . F b c d e e e f i i i i i i l l n n n o o o p p r r s t t t u v x y

Example 20.8, Page Number:482

In [9]:
import string

def qsort(p):
    """Quicksort using list comprehensions"""
    if p == []: 
        return []
    else:
        pivot = p[0]
        lesser = qsort([x for x in p[1:] if x < pivot])
        greater = qsort([x for x in p[1:] if x >= pivot])
        return lesser + [pivot] + greater
 
#Variable Declaration        
num=[10,4,3,6,5,7,8]

#sorting the string
num=qsort(num)

#Result
for i in range(7):
    print num[i],
3 4 5 6 7 8 10

Example 20.9, Page Number:484

In [10]:
def space(count,ch=None):
    if ch==None:
        for i in xrange(count,0,-1):
            print '',
    else:
        for i in xrange(count,0,-1):
            print ch,
            

fp1=space
fp2=space

fp1(22)           #outputs 20 spaces
print "|\n"        

fp2(30,'x')       #output 30 xs 
print "|\n"
        
                      |

x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x |

Example 20.10, Page Number:485

In [11]:
num=None  #static variable

class ShareVar:
    def setnum(i=0):
        global num
        num=i
    def shownum(self):
        global num
        print num
    
#Variables declaration
a=ShareVar()
b=ShareVar()

a.shownum()        #prints None
b.shownum()        #prints None

num=10             #set static num to 10

a.shownum()        #prints 10
b.shownum()        #prints 10
    
None
None
10
10

Example 20.11, Page Number:487

In [12]:
class Demo:
    i=None
    j=None
    def geti(self):
        return self.i
    def seti(self,x):
        self.i=x
    
ob=Demo()

ob.seti(1900)
print ob.geti()
1900

Example 20.12, Page Number:488

In [15]:
class myclass:
    def __init__(self,x):
        self.__a=x
    def geta(self):
        return self.__a
    
#Variable declaration
ob=myclass(4)

#Result
print ob.geta()
4

Example 20.13, Page Number:489

In [2]:
class myclass:
    def __init__(self,x):
        self.__a=x
    def geta():
        return self.__a
    
ob = myclass(110)

Example 20.14, Page Number:490

In [3]:
class myclass:
    def __init__(self,i):
        self.__num=i
    def getnum(self):
        return self.__num
    
#Variable declaration
o=myclass(10)

print o.getnum()          #display 10

o=myclass(1000)

print o.getnum()          #display 1000
10
1000

Example 20.15, Page Number:491

In [16]:
class myclass:
    def __init__(self,x,y):
        self.__numA=x
        self.__numB=y
    def getnumA(self):
        return self.__numA
    def getnumB(self):
        return self.__numB
        
#Variable declaration
ob1=myclass(7,9)
ob2=myclass(5,2)

#Result
print "Values in ob1 are ",ob1.getnumB(),"and",ob1.getnumA()
print "Values in ob2 are ",ob2.getnumB(),"and",ob2.getnumA()
Values in ob1 are  9 and 7
Values in ob2 are  2 and 5

Example 20.16, Page Number:492

In [17]:
class myclass:
    def __init__(self,x,y):
        self.__numA=x
        self.__numB=y
    def getnumA(self):
        return self.__numA
    def getnumB(self):
        return self.__numB
        
#Variable declaration
ob1=myclass(7,9)
ob2=myclass(5,2)

#Result
print "Values in ob1 are ",ob1.getnumB(),"and",ob1.getnumA()
print "Values in ob2 are ",ob2.getnumB(),"and",ob2.getnumA()
Values in ob1 are  9 and 7
Values in ob2 are  2 and 5

Example 20.17, Page Number:494

In [18]:
def myfunc():
    print "This links as a C function."
    
myfunc()
This links as a C function.

Example 20.18, Page Number:495

In [4]:
from ctypes import *

class myclass:    
    sum=c_int(0)
    def sum_it(self,x):
        for i in range(x+1):
            self.sum.value+=i
    fp=sum_it                          #pointer to function

#Variable declaration
c=myclass()
fp=myclass.sum_it                      #get address of function
dp=pointer(c.sum)                      #address of data
c.fp(7)                                #compute summation of 7


#Result
print "summation of 7 is",dp[0]
        
summation of 7 is 28

Example 20.19, Page Number:496

In [6]:
from ctypes import *

class myclass:
    sum=c_int(0)
    def sum_it(self,x):                      
        for i in range(x+1):
            self.sum.value+=i
    fp=sum_it                          #pointer to function

#Variable declaration
d=myclass()
c=[d]                                  #ponter to object
fp=myclass.sum_it                      #get address of function
dp=pointer(c[0].sum)                   #get address of data

c[0].fp(7)                             #compute summation of 7


#Result
print "summation of 7 is",dp[0]
        
 summation of 7 is 28

Example 20.20, Page Number:497

In [1]:
class three_d:
    def __init__(self,a,b,c):   #3D coordinates
        self.x=a
        self.y=b
        self.z=c
    #Display x,y,z coordinates - three_d inserter.
    def __repr__(self):
        return str(self.x)+", "+str(self.y)+", "+str(self.z)+"\n"
    def __add__(self,op2):
        if isinstance(op2,int):
            c=self.x*self.y*self.z+op2
            return c
        temp=three_d(self.x+op2.x,self.y+op2.y,self.z+op2.z)
        return temp
    
a=three_d(1,2,3)
b=three_d(2,3,4)

print a,b,

print b+100               #displays 124 because of conversion to int

a=a+b                     #add two three_d objects - no conversion

print a                   #displays 3,5,7
1, 2, 3
 2, 3, 4
 124
3, 5, 7

In [ ]: