"self" - a python wart or "feature"

Cere Davis cere at u.washington.edu
Tue Feb 18 05:39:32 EST 2003


Bengt Richter wrote:

>  
>
>>    
>>
>In your example, you don't explicitly use self, so it seems useless.
>Try writing an example that sets instance attributes and uses class
>variables and also makes use of temporary local variables in a method.
>  
>

How about:
y=4
class C:
    def __init__(self):
        self.z=2
        self.x=1
    def stuff(self, x=5):
        y=1
        print  x + y + self.z  # should equal  x + 1 + 2
        y= globals()['y']
        print x + y + self.z  # should equal x + 4 + 2

c.stuff() should be:
5
7

What I wish for - but am not sure if it's possible - is that the 
function "stuff" could just be declared as"def  stuff(x=5)".
The self references within the "stuff" function would be "known" to the 
function by the level of it's "indentedness".  
It just seems odd to me to have to tell a function which instance it 
should bind to in the first argument of the function declaration.


>If you need more to think about, try passing a bound (to an instance)
>method as an executable to something like map.
>
>And then ask you question again, or propose some workable alternatives ;-)
>Sorry to be a little lazy, but I'm not feeling like doing examples just now ;-)
>
>Regards,
>Bengt Richter
>  
>






More information about the Python-list mailing list