Chapter 6: Objects and Classes

Example 6.1, Page Number: 216

In [1]:
class smallobj:                   #define a class
    
    def setdata(self,d):          #member function to set class variable somdata
        self.__somedata = d
        
    def showdata(self):           #member function to display somedata 
        print 'Data is' , self.__somedata

        

#define two objects of class smallobj
s1=smallobj()
s2=smallobj()

#call member function to set data 
s1.setdata(1066)
s2.setdata(1776)

#call member function to display data 
s1.showdata()
s2.showdata()
Data is 1066
Data is 1776

Example 6.2, Page Number: 223

In [2]:
class part:                              #define class 
    
    def setpart(self,mn,pn,c):           #set data
        self.__modelnumber = mn
        self.__partnumber = pn
        self.__cost = c
    
    def showpart(self):                  #display data 
        print 'Model' , self.__modelnumber ,
        print ', part' , self.__partnumber , 
        print ', costs $',self.__cost
        
        
#define object of class part     
part1 = part()

#call member function setpart
part1.setpart(6244,373,217.55)

#call member function showpart
part1.showpart()
Model 6244 , part 373 , costs $ 217.55

Example 6.3, Page Number: 225

In [3]:
from turtle import Turtle,setup,done              #importing turtles library

class circle:                     #defining circle class
    
    def set(self,x,y,r,fc):       #sets circle attribute
        self._xCo = x
        self._yCo = y
        self._radius = r
        self._fillcolor = fc
        
    def draw(self):                          #draws the circle 
        setup()                              #set screen
        turtle = Turtle()                    #object of Turtle class
        turtle.begin_fill()                  #start filling color in circle
        turtle.color(self._fillcolor)        #color
        turtle.up()
        turtle.goto(self._xCo,self._yCo)     #set center of circle
        turtle.circle(self._radius)          #draw circle of radius self.__radius
        turtle.end_fill()                    #stop filling
        turtle.hideturtle()
        done()

        
        
#creating objects of class circle       
c1 = circle()
c2 = circle()
c3 = circle()

#sending the value to set fnction
c1.set(15,7,5,"blue")
c2.set(41,12,7,"red")
c3.set(65,18,4,"green")

#draw circle
c1.draw()
c2.draw()
c3.draw()

#In the above example the cirlcle's in the book are constructed using 'X' and 'O' but such feature is not available in Python.
#So i have created a simple circle filled with color

Example 6.4, Page Number: 226

In [4]:
class Distance:                   #Distance class
    
    def setdist(self,ft,inc):     #set distance to class variables
        self.__feet = ft
        self.__inches = inc
    
    def getdist(self):            #get distance from user
        self.__feet = input('Enter feet:')
        self.__inches = input('Enter inches:')
    
    def showdist(self):           #display distance
        print self.__feet , '\' -' , self.__inches , '\"'

        
        
#define two distance
dist1 = Distance()
dist2 = Distance()

dist1.setdist(11,6.25)   #set dist1
dist2.getdist()     #set dist2 from user

#show distances
print "\ndist1 = ",
dist1.showdist()
print 'dist2 = ',
dist2.showdist()
Enter feet:10
Enter inches:4.75

dist1 =  11 ' - 6.25 "
dist2 =  10 ' - 4.75 "

Example 6.5, Page Number: 228

In [5]:
class Counter:                       #class counter
    
    def __init__(self):              #constructor
        self.__count = 0
    
    def inc_count(self):             #increment count
        self.__count = self.__count + 1
    
    def get_count(self):             #return count
        return self.__count

    
    
#define and initialize class objects
c1=Counter()
c2=Counter()

#display count for each object
print 'c1 =',c1.get_count()
print 'c2 =',c2.get_count()


c1.inc_count()    #increment c1
c2.inc_count()    #increment c2
c2.inc_count()    #increment c2

#display count again for each object
print 'c1 =',c1.get_count()
print 'c2 =',c2.get_count()
c1 = 0
c2 = 0
c1 = 1
c2 = 2

Example 6.6, Page Number: 231

In [6]:
from turtle import Turtle,setup,done       #importing turtles library

class circle:          #defining circle class
    
    def __init__(self,x,y,r,fc):     #constructor for set circle attribute
        self._xCo = x
        self._yCo = y
        self._radius = r
        self._fillcolor = fc
        
    def draw(self):      #draws the circle
        setup()
        turtle = Turtle()
        turtle.begin_fill()
        turtle.color(self._fillcolor)
        turtle.up()
        turtle.goto(self._xCo,self._yCo)
        turtle.down()
        turtle.circle(self._radius)
        turtle.end_fill()
        turtle.hideturtle()
        done()

        
        
#creating objects of class circle        
c1 = circle(15,7,5,"blue")   
c2 = circle(41,12,7,"red")
c3 = circle(65,18,4,"green")

#draw circle
c1.draw()
c2.draw()
c3.draw()

Example 6.7, Page Number: 233

In [7]:
class Distance:                      #Distance class
    
    def __init__(self,ft=0,inc=0):   #constructor 
        self.__feet = ft
        self.__inches = inc
    
    def getdist(self):               #get length from user
        self.__feet = input('Enter feet:')
        self.__inches = input('Enter inches:')
    
    def showdist(self):              #display distance
        print self.__feet , '\' -' , self.__inches , '\"'
    
    def add_dist(self,d2,d3):        #add length d2 and d3
        
        self.__inches = d2.__inches + d3.__inches      #add inches
        self.__feet = 0
        
        if self.__inches >= 12.0:                      #if total exceeds 12.0
            self.__inches = self.__inches - 12.0       #then decrease inches by 12.0
            self.__feet = self.__feet + 1              #and increase feet by 1
            
        self.__feet = self.__feet + d2.__feet + d3.__feet       #add the feet

        
        
        
#define two length
dist1 = Distance()
dist3 = Distance()

#define and initialize dist2
dist2 = Distance(11,6.25)

#get dist1 from user
dist1.getdist()

#dist3 = dist1 + dist2
dist3.add_dist(dist1,dist2)

#display all lengths
print '\ndist1 = ',
dist1.showdist()
print 'dist2 = ',
dist2.showdist()
print 'dist3 = ',
dist3.showdist()
Enter feet:17
Enter inches:5.75

dist1 =  17 ' - 5.75 "
dist2 =  11 ' - 6.25 "
dist3 =  29 ' - 0.0 "

Example 6.8, Page Number: 238

In [8]:
class Distance:        #Distance  class
    
    def __init__(self,ft=0,inc=0):  #overloaded constructor that takes no arguments or two args or one object(copy constructor)
        
        if isinstance(ft,int):
            self.__feet = ft
            self.__inches = inc
        else:
            self.__feet = ft.__feet
            self.__inches = ft.__inches
            
    def getdist(self):      #get length from user
        self.__feet = input('Enter feet:')
        self.__inches = input('Enter inches:')
    
    def showdist(self):     #display distance
        print self.__feet , '\' -' , self.__inches , '\"'

        
        
#two argument constructor
dist1 = Distance(11,6.25)

#one argument(object) constructor explicitly pass
dist2 = Distance(dist1)

#also one argument(object) constructor implicitly pass
dist3 = dist1

#display all lengths
print 'dist1 = ',
dist1.showdist()
print 'dist2 = ',
dist2.showdist()
print 'dist3 = ',
dist3.showdist()
dist1 =  11 ' - 6.25 "
dist2 =  11 ' - 6.25 "
dist3 =  11 ' - 6.25 "

Example 6.9, Page Number: 240

In [9]:
class Distance:        #Distance class
    
    def __init__(self,ft=0,inc=0):     #constructor 
        self.__feet = ft
        self.__inches = inc
    
    def getdist(self):         #get length from user
        self.__feet = input('Enter feet:')
        self.__inches = input('Enter inches:')
    
    def showdist(self):        #display distance
        print self.__feet , '\' -' , self.__inches , '\"'
    
    def add_dist(self,d2):                                  #add this length to d2 and return object
        temp = Distance()                                   #temporary object
        temp.__inches = self.__inches + d2.__inches
        
        if temp.__inches >= 12.0:
            temp.__inches = temp.__inches - 12.0
            temp.__feet = 1
            
        temp.__feet = temp.__feet + self.__feet + d2.__feet
        return temp                                         #return sum as object

    
    
#define two length
dist1 = Distance()
dist3 = Distance()

#define and initialize dist2
dist2 = Distance(11,6.25)

#get dist1 from user
dist1.getdist()

#dist3 = dist1 + dist2
dist3 = dist1.add_dist(dist2)

#display all lengths
print '\ndist1 = ',
dist1.showdist()
print 'dist2 = ',
dist2.showdist()
print 'dist3 = ',
dist3.showdist()
Enter feet:17
Enter inches:5.75

dist1 =  17 ' - 5.75 "
dist2 =  11 ' - 6.25 "
dist3 =  29 ' - 0.0 "

Example 6.10, Page Number: 243

In [10]:
Suit = ["clubs","diamonds","hearts","spades"]  

(clubs,diamonds,hearts,spades) = (0,1,2,3)    #Atteching the names with number  


#from 2 to 10 are integers without names
jack = 11      
queen = 12 
king = 13
ace = 14


class card:       
    
    def __init__(self,n=None,s=None):       #constructor
        self.__number = n                   #2 to 10, jack, queen, king, ace
        self.__suit = s                     #clubs, diamonds, hearts, spades
    
    
    def display(self):                      #display the cards
        
        if self.__number >= 2 and self.__number<=10:
            print self.__number , 'of',
            
        else:
            if self.__number == jack:
                print 'jack of',
            elif self.__number == queen:
                print 'queen of',
            elif self.__number == king:
                print 'king of',
            else:
                print 'ace of',
                
        if self.__suit == clubs:
            print 'clubs',
        elif self.__suit == diamonds:
            print 'diamonds',
        elif self.__suit == hearts:
            print 'hearts',
        else:
            print 'spades',
    
    
    def isEqual(self,c2):           #return 1 if cards equal
        
        if self.__number == c2.__number and self.__suit == c2.__suit:
            return 1
        else:
            return 0


        
        
#define various cards
temp = card()
chosen = card()
prize = card()


#define and initialize card1
card1 = card(7,clubs)
print 'card 1 is the',
card1.display()    #display card1

#define and initialize card2
card2 = card(jack,hearts)
print 'card 2 is the',
card2.display()    #display card2

#define and initialize card3
card3 = card(ace,spades)
print 'card 3 is the',
card3.display()    #display card3


#prize is the card to guess
prize = card3


#swapping cards
print '\nI\'m swapping card 1 and card 3'
temp = card3
card3 = card1
card1 = temp

print 'I\'m swapping card 2 and card 3'
temp = card2
card2 = card3
card3 = temp

print 'I\'m swapping card 1 and card 2'
temp = card2
card2 = card1
card1 = temp

print 'Now, where (1,2, or 3) is the',
prize.display()          #display prize
print '?',


position = input("  ")       #get user's guess of position


#set chosen to user's choice 
if position == 1:
    chosen = card1
elif position == 2:
    chosen = card2
else:
    chosen = card3

    
#is chosen card the prize?
x=chosen.isEqual(prize)


if x==1:
    print 'That\'s right! You win!'
else:
    print 'Sorry. You lose.'

print ' You choose the',


#display chosen card
chosen.display()
card 1 is the 7 of clubs card 2 is the jack of hearts card 3 is the ace of spades 
I'm swapping card 1 and card 3
I'm swapping card 2 and card 3
I'm swapping card 1 and card 2
Now, where (1,2, or 3) is the ace of spades ?  1
 Sorry. You lose.
 You choose the 7 of clubs

Example 6.11, Page Number: 249

In [11]:
class foo: 
    
    __count = 0     #only one data item for all objects
    
    def __init__(self):
        foo.__count = foo.__count + 1     #increment count when object created
    
    def getcount(self):        #returns count
        return foo.__count

    
    
#create three objecs
f1 = foo()
f2 = foo()
f3 = foo()

#Each object displays the same count value
print 'count is', f1.getcount()
print 'count is', f2.getcount()
print 'count is', f3.getcount()
count is 3
count is 3
count is 3

Example 6.12, Page Number: 253

In [12]:
class Distance:         #Distance class
    
    def __init__(self,ft=0,inc=0.0):        #constructor 
        self.__feet = ft
        self.__inches = inc
    
    def getdist(self):              #get length from user
        self.__feet = input('Enter feet:')
        self.__inches = input('Enter inches:')
    
    def showdist(self):             #display distance
        print self.__feet , '\' -' , self.__inches , '\"'

        
    #There's no const keyword 
    
    def add_dist(self,d2):          #add this length to d2 and return object
        
        temp = Distance()
        temp.__inches = self.__inches + d2.__inches
        
        if temp.__inches >= 12.0:
            temp.__inches = temp.__inches - 12.0
            temp.__feet = 1
            
        temp.__feet = temp.__feet + self.__feet + d2.__feet
        
        return temp                  #return sum as object
    
    
    
#define two length
dist1 = Distance()
dist3 = Distance()

#define and initialize dist2
dist2 = Distance(11,6.25)

#get dist1 from user
dist1.getdist()

dist3 = dist1.add_dist(dist2)

#display all lengths
print '\ndist1 = ',
dist1.showdist()
print 'dist2 = ',
dist2.showdist()
print 'dist3 = ',
dist3.showdist()
Enter feet:17
Enter inches:5.75

dist1 =  17 ' - 5.75 "
dist2 =  11 ' - 6.25 "
dist3 =  29 ' - 0.0 "

Example 6.13, Page Number: 255

In [13]:
class Distance:                          #class distance
    
    def __init__(self,ft,inc):           #constructor
        self.__feet = ft
        self.__inches = inc
    
    def getdist(self):                  #get distance from user
        self.__feet = input('Enter feet:')
        self.__inches = input('Enter inches:')
    
    def showdist(self):                 #display the distance
        print self.__feet , '\' -' , self.__inches , '\"'

        
#initialize distance object
football = Distance(300,0)

print 'football = ',
football.showdist()

#There's no const keyword in python
football =  300 ' - 0 "
In [ ]: