We can create our own custom type (as opposed to Python's built-in types) by defining classes. In a class definition, we specify what an instance of a class should have as data--the object attributes--and what an instance can do--methods. We can also create variables to store values that are shared by all instances of a class--class attributes.
College
and Showdown
in Assignment 3 and the classes Reader
and Book
in Assignment 2.
OR read Chapter 15 on classes and objects and 17.1 - 17.5 on defining methods
Syntax note: The class header can be written in different ways in Python 3.x. For a simple class, we, and the author of our textbook, write the class header as class classname:. For example, if we define a class Point
, then the class definition would begin with this line of code: class Point:
If you look at Python code from other sources, however, you may see class Point():
or class Point(object):
as the class header. These three ways of writing the class header are equivalent in Python 3 (but not in Python 2). We will explain the details of this syntax in a couple of weeks, after you learn more about classes.
Slides: individual slides for viewing, 6-up layout for printing
Examples:
college_simple.py,
college.py
To download the above .py files, right-click (Windows) or command-click (Macs) on the filename and then select "Save link as".
This way you choose where the files will be saved, instead of having your computer save to the default folder (from which you will later have to move your files for organization).
Answers to the questions on slides 40 and 42: See the lecture slides file above for the questions. To answer the question on slide 40, first predict what should happen. Then modify function enroll
in college.py as shown on the slide and run the script. What happens? Do you understand the result? After solving the problems yourself, you can check your answers here.