Page 228 -
P. 228

note to self


          The importance of self


           To confirm: when you define a class you are, in effect, defining a custom factory
           function that you can then use in your code to create instances:




              The target identifier that holds     a = Athlete()              Invoke the class’s custom factory
                                                                              function.
              a reference to your instance


           When Python processes this line of code, it turns the factory function call into
           the following call, which identifies the class, the method (which is automatically
           set to __init__()), and the object instance being operated on:



                The name of the class
                                                                               The target identifier

                                           Athlete().__init__(a)                of the object instance



                                                   The name of the method

           Now take another look at how the __init__() method was defined in the
           class:



                        def __init__(self):

                              # The code to initialize an "Athlete" object.
                                    ...



           Check out what Python turns your object creation invocation into. Notice
           anything?


           The target identifer is assigned to the self argument.
          This is a very important argument assignment. Without it, the Python interpreter
           can’t work out which object instance to apply the method invocation to. Note
           that the class code is designed to be shared among all of the object instances:
           the methods are shared, the attributes are not. The self argument helps
           identify which object instance’s data to work on.




           192    Chapter 6
   223   224   225   226   227   228   229   230   231   232   233