# Chapter 9: Inheritance¶

## Example 9.1, Page Number 374¶

In [2]:
class Counter(CountDn):                         #base class

def __init__(self,c=0):                     #constructor
self._count = c                         #not private

def get_count(self):                        #return count
return self._count

self._count += other
return Counter(self._count)

class CountDn(Counter):                         #derived class

def __isub__(self,other):                   #decrement count
self._count -= other
return Counter(self._count)

c1 = CountDn()                                  #c1 of class CountDn

print 'c1 =',c1.get_count()                     #display c1

c1 += 1                                         #increment count 3 times
c1 += 1
c1 += 1
print 'c1 =',c1.get_count()                     #display count

c1 -= 1                                         #decrement c1, twice
c1 -= 1
print 'c1 =',c1.get_count()                     #display c1

c1 = 0
c1 = 3
c1 = 1


## Example 9.2, Page Number 380¶

In [2]:
class Counter:                                #base class
def __init__(self,c=0):                   #constructor
self._count = c

def get_count(self):                      #return count
return self._count

self._count += other
return Counter(self._count)

class CountDn(Counter):                       #derived class
def __init__(self,c=0):                   #constructor
self._count = c

def __isub__(self,other):                 #decrement count
self._count -= 1
return CountDn(self._count)

c1 = CountDn()                          #class CountDn
c2 = CountDn(100)

print 'c1 =',c1.get_count()             #display
print 'c2 =',c2.get_count()

c1 += 1                                 #increment c1
c1 += 1
c1 += 1
print 'c1 =',c1.get_count()             #display c1

c2 -= 1                                 #decrement c2
c2 -= 1
print 'c2 =',c2.get_count()             #display it

c3 = CountDn()                          #create c3
c2 -= 1                                 #decrement c2
c3 = c2                                 #assign count value of c2 to c3
print 'c3 =',c3.get_count()             #display c3

c1 = 0
c2 = 100
c1 = 3
c2 = 98
c3 = 97


## Example 9.3, Page Number 382¶

In [3]:
class Stack:
_MAX = 3                                      #size of stack array
_st = [None]*_MAX                             #stack

def __init__(self):                           #constructor
self._top = -1

def push(self,var):                           #put number on stack
self._top += 1
self._st[self._top] = var

def pop(self):                                #take number off stack
x = self._st[self._top]
self._top -= 1
return x

class Stack2(Stack):

def push(self,var):                           #put number on stack

if self._top >= self._MAX-1:              #error if stack full
print 'Error: stack is full'
else:
Stack.push(self,var)                  #call push() in Stack class

def pop(self):                                #take number off stack
if self._top < 0:                         #error if stack empty
return 'Error: stack is empty'
else:
return Stack.pop(self)                #call pop() in Stack class

s1 = Stack2()

s1.push(11)                        #push some values onto stack
s1.push(22)
s1.push(33)

print s1.pop()                     #pop some values from stack
print s1.pop()
print s1.pop()
print s1.pop()                     #oops, popped one too many...

33
22
11
Error: stack is empty


## Example 9.4, Page Number 385¶

In [4]:
class Distance:                                                 #Distance class

def __init__(self,ft=0,inc=0):                              #constructor
self._feet = ft                                         #can't be private
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 , '\"'

class DistSign(Distance):                                   #adds sign to distance

def __init__(self,ft=0,inc=0,sg='pos'):                 #constructor
Distance.__init__(self,ft,inc)                      #call base class constructor
self._sign = sg                                     #sign is pos or neg

def getdist(self):                                      #get length from  user
Distance.getdist(self)                              #call base getdist()

ch = raw_input("Enter sign (+ or -): ")             #get sign from user
if ch == '+':
self._sign = 'pos'
else:
self._sign = 'neg'

def showdist(self):                                     #display distance
if self._sign == 'pos':                             #show sign
print '(+)',
else:
print '(-)',
Distance.showdist(self)                             #show ft and in

alpha = DistSign()                           #object with no arg constructor
alpha.getdist()                              #get alpha from user

beta = DistSign(11,6.25)                     #object with 2 - arg constructor

gamma = DistSign(100,5.5,'neg')              #object with 3 - arg constructor

print '\nalpha =',                           #display all distances
alpha.showdist()
print 'beta =',
beta.showdist()
print 'gamma =',
gamma.showdist()

Enter feet: 6
Enter inches: 2.5
Enter sign (+ or -): -

alpha = (-) 6 ' - 2.5 "
beta = (+) 11 ' - 6.25 "
gamma = (-) 100 ' - 5.5 "


## Example 9.5, Page Number 389¶

In [5]:
LEN = 80                              #maximum length

class employee:                                                #employee class
__name = [None]*LEN                                        #employee name

def getdata(self):                                         #get data from user
self.__name = raw_input("   Enter last name: ")
self.__number = input("   Enter number: ")             #employee number

def putdata(self):                                         #display data
print '   Name:',self.__name
print '   Number:',self.__number

class manager(employee):                                       #management class
__title = [None]*LEN                                       #'vice-president' etc.

def getdata(self):
employee.getdata(self)
self.__title = raw_input("   Enter Title: ")
self.__dues = input("   Enter golf club dues: ")       #golf club dues

def putdata(self):
employee.putdata(self)
print '   Title:',self.__title
print '   Number:',self.__dues

class scientist(employee):                                     #scientist class
def getdata(self):
employee.getdata(self)
self.__pubs = raw_input("   Enter Number of pubs: ")   #number of publication

def putdata(self):
employee.putdata(self)
print '   Number of publications:',self.__pubs

class laborer(employee):             #labour class
pass

m1 = manager()
m2 = manager()
s1 = scientist()
l1 = laborer()
#get data for several employees
print 'Enter data for manager 1'
m1.getdata()

print 'Enter data for manager 2'
m2.getdata()

print 'Enter data for scientist 1'
s1.getdata()

print 'Enter data for laborer 1'
l1.getdata()

#display data for several employees
print '\nData on manager 1'
m1.putdata()

print 'Data on manager 2'
m2.putdata()

print 'Data on scientist 1'
s1.putdata()

print 'Data on laborer 1'
l1.putdata()

Enter data for manager 1
Enter last name: Wainsworth
Enter number: 10
Enter Title: President
Enter golf club dues: 1000000
Enter data for manager 2
Enter number: 124
Enter Title: Vice-President
Enter golf club dues: 500000
Enter data for scientist 1
Enter last name: Hauptman-Frenglish
Enter number: 234234
Enter Number of pubs: 999
Enter data for laborer 1
Enter last name: jones
Enter number: 6546544

Data on manager 1
Name: Wainsworth
Number: 10
Title: President
Number: 1000000
Data on manager 2
Number: 124
Title: Vice-President
Number: 500000
Data on scientist 1
Name: Hauptman-Frenglish
Number: 234234
Number of publications: 999
Data on laborer 1
Name: jones
Number: 6546544


## Example 9.6, Page Number 393¶

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

class shape:                                   #base class
def __init__(self,x=0,y=0,fc="white"):     #constructor
self._xCo = x                          #coordinate for shape
self._yCo = y
self._fillcolor = fc                   #color for shape

class circle(shape):                 #defining circle class

def __init__(self,x,y,r,fc):     #constructor for set circle attribute
shape.__init__(self,x,y,fc)

def draw(self):      #draw the circle
setup()
turtle = Turtle()
turtle.begin_fill()
turtle.color(self._fillcolor)
turtle.up()
turtle.goto(self._xCo,self._yCo)
turtle.down()
turtle.end_fill()
turtle.hideturtle()
done()

class rect(shape):          #defining rectangle class

def __init__(self,x,y,h,w,fc):     #constructor
shape.__init__(self,x,y,fc)
self._height = h
self._weight = w

def draw(self):      #draw the rectangle
setup()
turtle = Turtle()
turtle.begin_fill()
turtle.color(self._fillcolor)
turtle.up()
turtle.goto(self._xCo,self._yCo)
turtle.down()
turtle.forward(self._weight)
turtle.left(90)
turtle.forward(self._height)
turtle.left(90)
turtle.forward(self._weight)
turtle.left(90)
turtle.forward(self._height)
turtle.end_fill()
turtle.hideturtle()
done()

class tria(shape):          #defining triangle class

def __init__(self,x,y,h,fc):     #constructor
shape.__init__(self,x,y,fc)
self._height = h

def draw(self):      #draw the triangle
setup()
turtle = Turtle()
turtle.begin_fill()
turtle.color(self._fillcolor)
turtle.up()
turtle.goto(self._xCo,self._yCo)
turtle.down()
turtle.forward(self._height)
turtle.left(120)
turtle.forward(self._height)
turtle.left(120)
turtle.forward(self._height)
turtle.end_fill()
turtle.hideturtle()
done()

cir = circle(40,12,5,"blue")                #create circle
rec = rect(12,7,10,15,"red")                #create rectangle
tri = tria(60,7,11,"green")                 #create triangle

#draw all shape
cir.draw()
rec.draw()
tri.draw()


## Example 9.7, Page Number 397¶

In [7]:
class A:                                    #base class
__privdataA = None                      #private variable
_protdataA = None                       #protected variable
pubdataA = None                         #public variable

class B(A):
def funct(self):
a = self.__privdataA
a = self._protdataA
a = self.pubdataA

class C(A):
def funct(self):
a = self.__privdataA
a = self._protdataA
a = self._pubdataA

objB = B()
#a = objB.privdataA                 #not accesible because private variable
#a = objB.protdataA                 #not accesible because protected variable
a = objB.pubdataA

objC = C()
#a = objC.privdataA                 #not accesible because private variable
#a = objC.protdataA                 #not accesible because protected variable
a = objC.pubdataA            #In python, there is no concept of public or private inheritance so this line won't show any arror


## Example 9.8, Page Number 400¶

In [8]:
LEN = 80                                     #maximum length of names

class employee:                                                #employee class
__name = [None]*LEN                                        #employee name

def getdata(self):                                         #get data from user
self.__name = raw_input("   Enter last name: ")
self.__number = input("   Enter number: ")             #employee number

def putdata(self):                                         #display data
print '   Name:',self.__name
print '   Number:',self.__number

class manager(employee):                                       #management class
__title = [None]*LEN                                       #'vice-president' etc.

def getdata(self):
employee.getdata(self)
self.__title = raw_input("   Enter Title: ")
self.__dues = input("   Enter golf club dues: ")       #golf club dues

def putdata(self):
employee.putdata(self)
print '   Title:',self.__title
print '   Number:',self.__dues

class scientist(employee):                                     #scientist class
def getdata(self):
employee.getdata(self)
self.__pubs = raw_input("   Enter Number of pubs: ")   #number of publication

def putdata(self):
employee.putdata(self)
print '   Number of publications:',self.__pubs

class laborer(employee):                                       #laborer class
pass

class foreman(laborer):                                        #foreman class
def getdata(self):
laborer.getdata(self)
self.__quotas = raw_input("   Enter quotas: ")         #percent of quotes met successfully

def putdata(self):
laborer.putdata(self)
print '   Quotas:',self.__quotas

l1 = laborer()
f1 = foreman()
#get data for several employees
print 'Enter data for laborer 1'
l1.getdata()

print 'Enter data for foreman 1'
f1.getdata()

#display data for several employees
print '\nData on laborer 1'
l1.putdata()

print 'Data on foreman 1'
f1.putdata()

Enter data for laborer 1
Enter last name: Jones
Enter number: 6546544
Enter data for foreman 1
Enter last name: Jones
Enter number: 6546544
Enter quotas: 100

Data on laborer 1
Name: Jones
Number: 6546544
Data on foreman 1
Name: Jones
Number: 6546544
Quotas: 100


## Example 9.9, Page Number 405¶

In [9]:
LEN = 80                              #maximum length of names

class student:                        #eduational background
__school = [None]*LEN             #name of school or university
__degree = [None]*LEN             #hightest degree earned

def getedu(self):
self.__school = raw_input("   Enter name of school or university: ")
print '   Enter highest degree earned '
self.__degree = raw_input("   (Highschool, Bachelor\'s, Master\'s, PhD): ")

def putedu(self):
print '   School or Uniersity:',self.__school
print '   Highest degree earned:',self.__degree

class employee:                      #employee class
__name = [None]*LEN              #employee name

def getdata(self):
self.__name = raw_input("   Enter last name: ")
self.__number = input("   Enter number: ")               #employee number

def putdata(self):
print '   Name:',self.__name
print '   Number:',self.__number

class manager(employee,student):              #management
__title = [None]*LEN                      #"vice-precident" etc.

def getdata(self):
employee.getdata(self)
self.__title = raw_input("   Enter Title: ")
self.__dues = input("   Enter golf club dues: ")        #golf club dues
student.getedu(self)

def putdata(self):
employee.putdata(self)
print '   Title:',self.__title
print '   Number:',self.__dues
student.putedu(self)

class scientist(employee,student):            #scientist
def getdata(self):
employee.getdata(self)
self.__pubs = raw_input("   Enter Number of pubs: ")        #number of publications
student.getedu(self)

def putdata(self):
employee.putdata(self)
print '   Number of publications:',self.__pubs
student.putedu(self)

class laborer(employee):             #labrer
pass

m1 = manager()
s1 = scientist()
s2 = scientist()
l1 = laborer()

#get data for several employee
print '\nEnter data for manager 1'
m1.getdata()

print '\nEnter data for scientist 1'
s1.getdata()

print '\nEnter data for scientist 2'
s2.getdata()

print '\nEnter data for laborer 1'
l1.getdata()

#display data for several employee
print '\n\nData on manager 1'
m1.putdata()

print '\nData on scientist 1'
s1.putdata()

print '\nData on scientist 2'
s2.putdata()

print '\nData on laborer 1'
l1.putdata()

Enter data for manager 1
Enter number: 12
Enter Title: Vice-President
Enter golf club dues: 100000
Enter name of school or university: Yale
Enter highest degree earned
(Highschool, Bachelor's, Master's, PhD): Bachelor's

Enter data for scientist 1
Enter last name: Twilling
Enter number: 764
Enter Number of pubs: 99
Enter name of school or university: MIT
Enter highest degree earned
(Highschool, Bachelor's, Master's, PhD): PhD

Enter data for scientist 2
Enter last name: Yang
Enter number: 845
Enter Number of pubs: 101
Enter name of school or university: Stanford
Enter highest degree earned
(Highschool, Bachelor's, Master's, PhD): Master's

Enter data for laborer 1
Enter last name: Jones
Enter number: 48323

Data on manager 1
Number: 12
Title: Vice-President
Number: 100000
School or Uniersity: Yale
Highest degree earned: Bachelor's

Data on scientist 1
Name: Twilling
Number: 764
Number of publications: 99
School or Uniersity: MIT
Highest degree earned: PhD

Data on scientist 2
Name: Yang
Number: 845
Number of publications: 101
School or Uniersity: Stanford
Highest degree earned: Master's

Data on laborer 1
Name: Jones
Number: 48323


## Example 9.10, Page Number 409¶

In [10]:
class Type:                                         #type of lumber

def __init__(self,di = "N/A",gr = "N/A"):       #constructor
self.__dimensions = di

def gettype(self):                              #get type from user
self.__dimensions = raw_input("   Enter nominal dimensions (2x4 etc.): ")

def showtype(self):                             #display type
print '   Dimensions:',self.__dimensions

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 , '\"'

class Lumber(Type,Distance):

def __init__(self,di=None,gr=None,ft=0,inc=0.0,qu=0,prc=0.0):            #constructor

Type.__init__(self,di,gr)                   #call type constructor
Distance.__init__(self,ft,inc)              #call Distance constructor

self.__quantity = qu                        #number of pieces
self.__price = prc                          #price of each piece

def getlumber(self):
Type.gettype(self)
Distance.getdist(self)

self.__quantity = input("   Enter quantity: ")
self.__price = input("   Enter price per piece: ")

def showlumber(self):
Type.showtype(self)
print '   Length: ',
Distance.showdist(self)
print '   price for',self.__quantity,'pieces: $',self.__price*self.__quantity siding = Lumber() #constructor with no argument print 'Siding data:' siding.getlumber() #get siding from user studs = Lumber("2x4","const",8,0.0,200,4.5) #constructor with 6 arguments print '\nSiding' #display lumber data siding.showlumber() print 'studs' studs.showlumber()  Siding data: Enter nominal dimensions (2x4 etc.): 3x4 Enter grade (rough, const, etc.): rough Enter feet: 5 Enter inches: 6.5 Enter quantity: 300 Enter price per piece: 19.5 Siding Dimensions: 3x4 Grade: rough Length: 5 ' - 6.5 " price for 300 pieces:$ 5850.0
studs
Dimensions: 2x4
Length:  8 ' - 0.0 "
price for 200 pieces: \$ 900.0


## Example 9.11, Page Number 413¶

In [11]:
class A:
def show(self):
print 'Class A'

class B:
def show(self):
print 'Class B'

class C(A,B):
pass

objC = C()            #object of class C
#objC.show()
A().show()
B().show()

Class A
Class B


## Example 9.12, Page Number 414¶

In [12]:
class A:
def func(self):
pass

class B(A):
pass
class C(A):
pass
class D(B,C):
pass

objD = D()
#objD.func()


## Example 9.13, Page Number 417¶

In [13]:
class student:                        #educational background

def getedu(self):
self.__school = raw_input("   Enter name of school or university: ")                #name of school or university
print '   Enter highest degree earned '
self.__degree = raw_input("   (Highschool, Bachelor\'s, Master\'s, PhD): ")         #heighest degree earned

def putedu(self):
print '   School or Uniersity:',self.__school
print '   Highest degree earned:',self.__degree

class employee:

def getdata(self):
self.__name = raw_input("   Enter last name: ")              #employee name
self.__number = input("   Enter number: ")                   #employee number

def putdata(self):
print '   Name:',self.__name
print '   Number:',self.__number

class manager:                          #management

__emp = employee()                  #object of class employee
__stu = student()                   #object of class student

def getdata(self):
self.__emp.getdata()
self.__title = raw_input("   Enter Title: ")                 #"vice-president" etc.
self.__dues = input("   Enter golf club dues: ")             #golf club dues
self.__stu.getedu()

def putdata(self):
self.__emp.putdata()
print '   Title:',self.__title
print '   Number:',self.__dues
self.__stu.putedu()

class scientist:                        #scientist

__emp = employee()                  #object of class employee
__stu = student()                   #object of class student

def getdata(self):
self.__emp.getdata()
self.__pubs = raw_input("   Enter Number of pubs: ")         #number of publications
self.__stu.getedu()

def putdata(self):
self.__emp.putdata()
print '   Number of publications:',self.__pubs
self.__stu.putedu()

class laborer:                          #laborer

__emp = employee()                  #object of class employee

def getdata(self):
self.__emp.getdata()
def putdata(self):
self.__emp.putdata()

m1 = manager()
s1 = scientist()
s2 = scientist()
l1 = laborer()

#get data for several employee
print '\nEnter data for manager 1'
m1.getdata()

print '\nEnter data for scientist 1'
s1.getdata()

print '\nEnter data for scientist 2'
s2.getdata()

print '\nEnter data for laborer 1'
l1.getdata()

#display data for several employee
print '\n\nData on manager 1'
m1.putdata()

print '\nData on scientist 1'
s1.putdata()

print '\nData on scientist 2'
s2.putdata()

print '\nData on laborer 1'
l1.putdata()

Enter data for manager 1
Enter number: 12
Enter Title: Vice-President
Enter golf club dues: 100000
Enter name of school or university: Yale
Enter highest degree earned
(Highschool, Bachelor's, Master's, PhD): Bachelor's

Enter data for scientist 1
Enter last name: Twilling
Enter number: 764
Enter Number of pubs: 99
Enter name of school or university: MIT
Enter highest degree earned
(Highschool, Bachelor's, Master's, PhD): PhD

Enter data for scientist 2
Enter last name: Yang
Enter number: 845
Enter Number of pubs: 101
Enter name of school or university: Stanford
Enter highest degree earned
(Highschool, Bachelor's, Master's, PhD): master's

Enter data for laborer 1
Enter last name: Jones
Enter number: 48323

Data on manager 1
Number: 12
Title: Vice-President
Number: 100000
School or Uniersity: Yale
Highest degree earned: Bachelor's

Data on scientist 1
Name: Yang
Number: 845
Number of publications: 99
School or Uniersity: Stanford
Highest degree earned: master's

Data on scientist 2
Name: Yang
Number: 845
Number of publications: 101
School or Uniersity: Stanford
Highest degree earned: master's

Data on laborer 1
Name: Jones
Number: 48323

In [ ]: