Professional Documents
Culture Documents
1 c l a s s ClassName :
2 <s t a t e m e n t −1>
3 .
4 .
5 .
6 <s t a t e m e n t −N>
method is not unique to class instances: other object types can have meth-
ods as well. For example, list objects have methods called append, insert,
Class variables are variables that belong to the class as a whole; there
is only one copy of each one. Instance variables or attributes is data that
belongs to individual objects; every object has its own copy of each one.
Member variables refer to both the class and instance variables that are
whole and have access only to class variables and inputs from the procedure
instance variables for the specific object they are called on, inputs, and class
variables.
Now what can we do with instance objects? The only operations under-
stood by instance objects are attribute references. There are two kinds of
1
The class here is Dog, which has method, spam. The command, Dog.spam,
Note that the function object, fcn_obj, is not an instance, nor does it
bound method was really just a thin wrapper around some function object,
of the class in which the method was defined. Thus, if someone wanted to
call fcn_obj as a function, they would have to pass an instance of class Dog
object, fcn_obj, it refers to the method, spam from class Dog. But this
time, the reference was obtained through the instance, doggo. To handle
This object is also a thin wrapper around the function object for the method.
However, this wrapper implicitly stores the original instance that was used
2
call the method, Dog.spam, with the instance, doggo, implicitly set as the
first argument:
1 >>> method obj = doggo . spam
2 >>> method obj ( )
3 ’ H e l l o World ! My name i s Woof ! ’
4 >>> method obj
5 <bound method Dog . spam o f < main . Dog o b j e c t a t 0 x0000000006083978>>
6 >>>
7 >>> Dog . spam ( doggo )
8 ’ H e l l o World ! My name i s Woof ! ’
but ‘bound methods’ still remain. So the command, Dog.spam, now returns
this instance. It therefore implicitly sets the first argument of the method it
3
Generally speaking, instance variables are for data unique to each in-
stance and class variables are for attributes and methods shared by all in-
But the tricks list in the following code should not be used as a class
variable because just a single list would be shared by all instances of Dog:
1 c l a s s Dog :
2 tricks = [] # mistaken use o f a c l a s s v a r i a b l e
3 def init ( s e l f , name ) :
4 s e l f . name = name
5 def add trick ( s e l f , t r i c k ) :
6 s e l f . t r i c k s . append ( t r i c k )
7