shape7: shape7.py

#
# Like shape7 Java example, uses inheritance;
# but also our Shape has constructor and args
#

#
# Definition of superclass Shape
#
class Shape: #//*1 Superclass Shape, has constructor with args
	def __init__ (self, xin, yin): #//*1
		self._x = xin #//*1
		self._y = yin #//*1

	def setPos (self, xin, yin):
		self._x = xin
		self._y = yin

#
# Definition of class Rect
#
class Rect (Shape): #//*2 Inherit from Shape

	# Constructor
	def __init__ (self, xin, yin, widin, htin):
		# Must call our superclass' constructor first
		Shape.__init__ (self, xin, yin) #//*3 Call super constructor with args

		self._wid = widin
		self._ht = htin

	def setSize (self, widin, htin):
		self._wid = widin
		self._ht = htin

	def draw (self):
		print ("Drawing rectangle at " + " " + str(self._x) + " " + str(self._y) + " " + str(self._wid) + " " + str(self._ht))

	def area (self):
		return self._wid * self._ht

#
# Definition of class Circle
#
class Circle (Shape): #//*2
	def __init__ (self, xin, yin, radin):
		Shape.__init__(self, xin, yin) #//*3

		self._rad = radin

	def setSize (self, radin):
		self._rad = radin

	def draw (self):
		print ("Drawing circle at " + " " + str(self._x) + " " + str(self._y) + " " + str(self._rad))

	def area (self):
		return self._rad * self._rad * 3.14159

#
# A main program for testing our objects
# (identical to the one in shape6.py)
#

# Instantiate and initialize the objects
r1 = Rect (10, 10, 50, 50) #//*4 Main program is unchanged
r2 = Rect (80, 10, 10, 100)
c1 = Circle (35, 90, 10)

# "Draw" them
r1.draw()
r2.draw()
c1.draw()

# Compute and print total area
print ("Total area = " + str(r1.area() + r2.area() + c1.area()))
[download file]