# Chapter 8: Classes, Objects & Methods¶

## example 8.1, page no. 132¶

In [3]:
class Rectangle:
length = 0
width = 0
def getData(self, x, y):
self.length = x
self.width = y
def rectArea(self):
area = self.length * self.width
return area

rect1 = Rectangle()
rect1.length = 15
rect1.width = 10
rect2 = Rectangle()
area1 = rect1.length*rect1.width
rect2.getData(20,12)
area2 = rect2.rectArea()
print "Area1 = ", area1
print "Area2 = ", area2

 Area1 =  150
Area2 =  240


## example 8.2, page no. 134¶

In [4]:
class Rectangle:
length = 0
width = 0
def __init__(self, x=0, y=0):
self.length = x
self.width = y
def rectArea(self):
return self.length * self.width
rect1 = Rectangle(15, 10)
area1 = rect1.rectArea()
print "Area1 = ", area1

Area1 =  150


## example 8.3, page no. 136¶

In [7]:
#there are no static methods in Python, we will use normal methods instead

class MathOperations:
def mul(self, x, y):
return x*y
def divide(self, x, y):
return x/y

obj = MathOperations()
a = obj.mul(4.0,5.0)
b = obj.divide(a,2.0)
print "b = ", b

b =  10.0


## example 8.3, page no. 137¶

In [9]:
class Nesting:
m = 0
n = 0
def __init__(self, x, y):
self.m = x
self.n = y
def largest(self):
if(self.m>=self.n):
return self.m
else:
return self.n
def display(self):
large = self.largest()
print "Largest Value: ", large

nest = Nesting(50, 40)
nest.display()

Largest Value:  50


## example 8.4, page no. 139¶

In [63]:
class Room(object):
def __init__(self, x, y):
self.length = x
def area(self):

class BedRoom(Room):
height = 0
def __init__(self, x, y, z):
Room.__init__(self, x, y)
self.height = z
def volume(self):

room1 = BedRoom(14, 12, 10)
area1 = room1.area()
volume1 = room1.volume()
print "Area = ", area1
print "Volume = ", volume1

Area =  168
Volume =  1680


## example 8.6, page no. 142¶

In [65]:
class Super(object):
x = 0
def __init__(self, x):
self.x = x
def display(self):
print "Super x = ", self.x

class Sub(Super):
y = 0
def __init__(self, x, y):
Super.__init__(self, x)
self.y = y
def display(self):
print "Super x = ", self.x
print "Sub y = ", self.y
s1 = Sub(100, 200)
s1.display()

Super x =  100
Sub y =  200


## example 8.7, page no. 145¶

In [1]:
class Exampleprg:
def __init__(self, *args):
for arg in args:
print "Hello ", arg

e = Exampleprg("John", "David", "Suhel")

Hello  John
Hello  David
Hello  Suhel