Page 227 -
P. 227
custom data objects
Use class to define classes
Python uses class to create objects. Every defined class has a special method
called __init__(), which allows you to control how objects are initialized.
Methods within your class are defined in much the same way as functions,
that is, using def. Here’s the basic form:
The keyword starts Give your class a nice,
the definition. descriptive name.
class Athlete: Don’t forget the colon!
def __init__(self):
# The code to initialize a "Athlete" object.
...
That’s a double underscore before The code that initializes each
and after the word “init”.
object goes in here.
Creating object instances
With the class in place, it’s easy to create object instances. Simply assign a call
to the class name to each of your variables. In this way, the class (together
with the __init__() method) provides a mechanism that lets you create
a custom factory function that you can use to create as many object
instances as you require:
The brackets tell Python to
create a new “Athlete” object,
which is then assigned to a
a = Athlete() variable.
All of these variables are b = Athlete()
unique and are “of type” c = Athlete()
Athlete. d = Athlete()
Unlike in C++-inspired languages, Python has no notion of defining a
constructor called “new.” Python does object contruction for you, and then
lets you customize your object’s initial state using the __init__() method.
you are here 4 191