self argument

James Logajan JamesL at Lugoj.Com
Sat Feb 26 14:16:56 EST 2000


Jason Stokes wrote:
> 
> london999 at my-deja.com wrote in message <8984mm$5pi$1 at nnrp1.deja.com>...
> >I am very new to Python, but it appears that every function defined in a
> >class must have self as a first variable name.
> 
> No.  You're just a little confused on a couple of points.  Firstly, member
> functions always receive the invoked upon class instance as the first
> argument.  The convention is to call this argument "self", but there's no
> requirement to do so.  Secondly, not all functions are members of a class.
> Functions that are not class members don't receive this implicit argument;
> this way, you can program in conventional functional or procedural style.
> 
> > Even better, it would be nice (probably too late
> >I know), if self was defined implicitly as the "this" pointer is in C++.
> 
> I'm not sure why Python's way was chosen, but you get used to it.

If self were defined implicitly, then you would have to explicitly define
local variables. This is, today you would do something like:

class C:
    def __init__(self, b):
        self.b = b
        self.x = self.y = 0
    def Func(self, a):
        t = a * self.b
        self.x = t * 2
        self.y = t + 2

If self were implicit, then variables like 't' would need to be declared.
That leads to some problems. The above might become:

class C:
    def __init__(self, b):
        b = local.b  # Arguments are local.
    def Func(self, a):
        local.t = local.a * b
        x = local.t * 2
        y = local.t + 2

Or they could be declared once anywhere in the scope:

class C:
    def __init__(self, b): 
        b = local.b  # Still need to 
    def Func(self, a):
        local t = a * b
        x = t * 2
        y = t + 2


I think I like the way the language was designed.



More information about the Python-list mailing list