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 .
Or Read: Chapter 15 , 17.1 - 17.5
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).