Page 229 -
P. 229
custom data objects
Every method’s first argument is self
In fact, not only does the __init__() method require self as its first
argument, but so does every other method defined within your class.
Python arranges for the first argument of every method to be the invoking
(or calling) object instance. Let’s extend the sample class to store a value in a
object attribute called thing with the value set during initialization. Another
method, called how_big(), returns the length of thing due to the use of
the len() BIF:
class Athlete:
The “init” code now def __init__(self, value=0):
assigns a supplied value self.thing = value Note the use of
to a class attribute def how_big(self): “self” to identify
called “self.thing”. return(len(self.thing)) instance.
the calling object
The “how_big()” method returns the
length of “self.thing”.
When you invoke a class method on an object instance, Python arranges for
the first argument to be the invoking object instance, which is always assigned
to each method’s self argument. This fact alone explains why self is
so important and also why self needs to be the first argument to every object
method you write:
What you write: What Python executes:
d = Athlete("Holy Grail") Athlete.__init__(d, "Holy Grail")
The target
The class The method indentifer (or
instance)
d.how_big() Athlete.how_big(d)
you are here 4 193