Unification of Methods and Functions

David MacQuigg dmq at gain.com
Tue Jun 1 11:43:25 EDT 2004


Sorry for the late reply on this question.  I just now saw this post
in reviewing the thread.

On Fri, 14 May 2004 12:35:48 -0400, Rich Krauter <rmkrauter at yahoo.com>
wrote:

>On Thu, 2004-05-13 at 17:59, David MacQuigg wrote:

>> Actually, .var could be used in a function outside a class, just as
>> you can now use self.var in the current function syntax.  Before using
>> a function with .var, the global variable __self__ must be set.
>
>I may be way off here, but I don't see how a global __self__ could work:
>
><not python>
>
>class B:
>    def __init__(name,data):
>        .data = data*5
>        .name = '***%s***'%name
>
>class A:
>    def __init__(name,data):
>        .data = data  # __self__ is a?
>        .obj = B()    # __self__ is now the B instance?
>        .name = name  # now what?
>
>a = A()
>
></not python>

The __self__ variable is set automatically when a function is called
from an instance, and returned to its prior value ( usually None )
when the call returns.  So in the example above, we have an implicit
call to __init__ from the new instance a.  This makes the first line
of the __init__ function equivalent to a.data = data.

The second line is equivalent to a.obj = B().  When the new instance
of B is constructed, there is a call to its __init__ function from
that new instance.  At that moment, __self__ is set to the new
instance (a.obj), and that instance gets two new attributes, data and
name.

On returning from the call to B.__init__, __self__ returns to its
prior value 'a', and we set the final attribute a.name  When you are
done, there will be one instance a, with attributes data, name, and
obj.  The obj attribute is an instance of B, with attributes data and
name.

It works just like in current Python, except that the current instance
is "passed" by pointing to it with a special variable, rather than
inserting it into the argument sequence.  The key difference is that
when you use the first argument for passing an instance, that instance
is *required* in every call, even if it is not used. (Hence the need
for special syntax when we want to avoid this requirement.)  If you
use a global variable to pass the current instance, any function that
doesn't require it simply ignores it.

-- Dave




More information about the Python-list mailing list