you're reading...

Introduction to Modules and OOP in Python

OOP Course Notes: PowerPoint presentation Chapter10 from Zelle textbook

OOP is a methodolgy for packaging and reusing code. Typically, code refered to as classes and objects will be packaged in modules so that it can be imported into a client application.  Let look at how modules are imported in python.

Code is often stored in modules and each language provides mechanism to include the code and what names are to be used to reference it. Recall #include in C++.

In Python there are three formats of the command for importing code:
import somefile
from somefile import *
from somefile import className

import somefile

Everything in somefile.py gets imported.
To refer to something in the file, you have to append the text “somefile.” to the front of it: e.g., somefile.myFunction(34)

from somefile import *

Everything in somefile.py gets imported. You can just use the name of the stuff in the file. It’s all brought into the current namespace. This is generally the import method we will use, however, there is danger when using this import command, as you could overwrite the definition of something in your file!

from somefile import className

Only one item in somefile.py gets imported. You can just use the name of the item in the file. It’s brought into the current namespace. Be careful when using this import command, as you could overwrite the definition of this one name in your file!

What is Object-Oriented Programming (OOP) Methodology?

OOP is a methodology that allows for the packaging of code for reuse. This packaging is done differently in different languages, but generally there are 3 important aspects that all OOP implementations share.

Encapsulation: is the process of dividing the code into Classes with a public interface, and a private implementation of that interface. By limiting the functions you are going to support, you leave yourself free to change the internal data, enabling refactoring, and improving performance over time without messing up any of your code users.

Polymorphism: the ability to write functions or overload standard operators so that they have appropriate behavior based on their context. Ad hoc polymorphism is supported in many languages using function overloading, that is using the same function name applied to different data types. If code can be written to be used transparently with any number of new types, it is called parametric polymorphism.

Inheritance: the ability to create subclasses that contain specializations of their parents. Inheritance can be used to support polymorphism and encapsulation. Large system use inheritance to manage complexity.

Virtual function: this is a term used that indicates that a function’s behavior can be overridden within an inheriting class by a function with the same signature. This concept is an important part of the polymorphism. In python, since all variable types are determined dynamically at run time, all functions are virtual!

Objects and Classes:

Classes are factories for building objects. The collection of information stored inside an object is called instance variables. The operations that can be used with an object are called methods of the object. Collectively, the instance variables and methods are called the attributes of an object. New objects are created from a class by invoking a constructor. You can think of the class itself as a factory for stamping out new instances.


A Point object will have 2 floats as instance variables, and a draw method will plot that point on a graph. A Circle object will have instance variables such as center, which remembers the center point of the circle, and radius, which stores the length of the circle’s radius. The draw method for a circle, examines the center and radius to decide which pixels in a window should be colored. The move method applied to a point will change its two instance variable, and a move method for a circle will change the value its center to reflect the new position of the circle.

Consider constructing a new circle object:

myCircle = Circle(Point(0,0),20)

Circle, the name of the class, is used to invoke the constructor. Point is another class used to construct a point at the origin. The circle constructor takes a point object to specify its center, and uses a number (i.e., 20) as an argument for the radius. Once the instance has been created, it can be manipulated by calling on its methods:

myCircle.draw(win)    # note that the draw method takes a window object as argument.

A Cannonball Client

We will use a simple module for graphics (download graphics.py) to build an graphics application. The code below imports the library and simulates the flight of a cannonball.

The input to the program will be the launch angle (in degrees), the initial velocity (in meters per second), and the initial height (in meters) of the cannonball. The output will be the distance that the projectile travels before striking the ground (in meters).

Gravity: The acceleration of gravity near the earth’s surface is roughly 9.8 m/s/s. If an object is thrown straight up at 20 m/s, after one second it will be traveling upwards at 10.2 m/s. After another second, its speed will be .4 m/s. Shortly after that the object upward velocity will be 0 and will start coming back down to earth, using the same rate of change in velocity.

Using a little geometry, and the fact that the distance an object travels in a certain amount of time is equal to its rate times the amount of time (d = rt) we can produce a graphical simulation. We consider the flight of the cannonball in two dimensions: it’s height and the distance it travels. Let’s think of the position of the cannonball as the point (x, y) where x is the distance from the starting point and y is the height above the ground.

Design of Cannonball Graphics Program:

1. Input the simulation parameters: angle, velocity, height, time interval dtime.

2. Calculate the initial point position of the cannonball: xpos, ypos

3. Calculate the initial velocities of the cannonball: xvel, yvel

4. While the cannonball is still flying: Update how far the object moves in each dimension xmove, ymove, and then update values of xpos, ypos, and xvel, yvel for interval dtime seconds further into the flight. Using our simple graphics library methods we can update the position of the ball by calling the move method.


from math import *
from graphics import *
def main():
    win = GraphWin("My Cannonball",1000, 600)
    x0 = 0   #input("Enter the initial x-location (in meters): ")
    y0 = 20  #input("Enter the initial y-location height (in meters): ")
    ball = Circle(Point(x0,y0), 10)

    angle = 45   #input("Enter the launch angle (in degrees): ")
    vel = 90     #input("Enter the initial velocity (in meters/sec): ")
    dtime = 0.05 #input("Enter the time interval between position calculations: ")

    time = 0
    radians = (angle * pi)/180.0
    xpos = x0
    ypos = y0
    xvel = vel * cos(radians)
    yvel = vel * sin(radians)
    while ypos > 0:
        xmove =  xvel * dtime
        yvelnew = yvel - 9.8 * dtime
        ymove = dtime * (yvel + yvelnew)/2.0
        xpos = xpos + xmove
        ypos = ypos + ymove

        yvel = yvelnew
        time = time + dtime

    win.getMouse() # pause for click in window

Lab #6

Task 1: Convert the simulation so that the cannonball does not appear to be falling upside-down.
Task 2: Using the objects in the graphic library, add a cannon cylinder/rectangle and a flag near to where the cannonball is loaded.
Task 3: Create an animation that raises the flag before firing the cannon.
Extra Credit:
Task 4: Create a turn-based cannonball game by allowing for targets and user input.



No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: