CSC111 Example of Inheritance: Rectangle with a label
--D. Thiebaut 08:36, 8 December 2011 (EST)
# myRectangles.py
# D. Thiebaut
# Demonstration of inheritance with Python Classes
# In this program myRect inherits from Rectangle.
# Rectangle is the base class
# myRect is the derived class
# it adds a label in the center of the rectangle
from graphics import *
import time
class myRect( Rectangle ):
"""Derived class for a rectangle with a label in it"""
def __init__( self, P1, P2, label="Unknown" ):
"""Constructor for the class"""
#--- initializes the base class ---
Rectangle.__init__( self, P1, P2 )
#--- puts the lable in the middle ---
x1 = P1.getX()
y1 = P1.getY()
x2 = P2.getX()
y2 = P2.getY()
self.label = Text( Point( (x1+x2)/2, (y1+y2)/2 ), label )
def draw( self, win ):
""" draws the rectangle and the label """
Rectangle.draw( self, win )
self.label.draw( win )
def move( self, dx, dy ):
Rectangle.move( self, dx, dy )
self.label.move( dx, dy )
def main():
"""displays the graphics window and an instance of myRect"""
win = GraphWin( "Inheritance", 400, 400 )
r = myRect( Point( 20,20 ), Point( 150, 50 ), "Hello there!" )
r.draw( win )
#--- animation loop ---
while True:
r.move( random.choice( [-2, -1, 0, 1, 2 ] ), 0 )
if win.checkMouse() != None:
break
win.close()
main()