[Tutor] OOP Advice

Sean 'Shaleh' Perry shaleh@valinux.com
Tue, 6 Mar 2001 19:35:16 -0800


Teaching by example........

class Polyhedron:
	def __init__(self, sides):
		self.sides = sides

	def num_sides(self):
		return self.sides

class Rectangle(Polyhedron):
	def __init__(self, length, width):
		Polyhedron.__init__(self, 4)
		self.length = length
		self.width = width

	def area(self):
		return self.length * self.width

class Square(Rectangle):
	def __init__(self, length):
		Rectangle.__init__(self, length, length)

	# override the Parent's method
	def area(self):
		""" area of a Square is length of side * length of side """
		return self.length * self.length

if __name__ == '__main__':
	p = Polydron(5)
	print p.num_sides()
	
	r = Rectangle(4, 6)
	print r.num_sides()
	print r.area()

	s = Square(4)
	print s.num_sides()
	print s.area()


so, there is some inheritance, some poor planning (rectangle and square are
rather similar, no good reason to make a new class unless other methods would
care), and I hope a useful example.


python /tmp/geo.py 
5
4
24
4
16