Attack a sacred Python Cow

Michael Torrie torriem at gmail.com
Mon Jul 28 01:24:27 EDT 2008


Derek Martin wrote:
> Regardless of how it's implementd, it's such a common idiom to use
> self to refer to object instances within a class in Python that it
> ought to be more automatic.  Personally, I kind of like the idea of
> using @ and thinking of it more like an operator...  Kind of like
> dereferencing a pointer, only with an implied pointer name.
> 
>     class foo:
> 	def __init__():
> 	    @.increment = 2
> 
>     	def bar(a)
> 	    return a + @.increment
> 
> I'm sure all the Pythonistas will hate this idea though... ;-)  To be
> honest, it smacks a little of Perl's magic variables, which I actually
> hate with a passion.  This is the only place in Python I'd consider
> doing something like this.  

I think the biggest reason why an implicit self is bad is because it
prevents monkey-patching of existing class objects.  Right now I can add
a new method to any existing class just with a simple attribute like so
(adding a new function to an existing instance object isn't so simple,
but ah well):

def a(self, x, y):
    self.x = x
    self.y = y

class Test(object):
    pass

Test.setxy = a

b = Test()

b.setxy(4,4)

print b.x, b.y

If self was implicit, none of this would work. Now this contrived
example is not useful, and maybe not even correct, but I have patched
existing classes on several occasions using this method.  How could
python retain it's dynamic nature and still have an implicit self?  How
would the interpreter know when to add the self variable and when not to?



More information about the Python-list mailing list