Attack a sacred Python Cow

Nikolaus Rath Nikolaus at rath.org
Mon Jul 28 03:38:36 EDT 2008


Michael Torrie <torriem at gmail.com> writes:
> 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.

No, but it could work like this:

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

class Test(object):
     pass

Test.setxy = a
b = Test()

# Still all the same until here

# Since setxy is called as an instance method, it automatically
# gets a 'self' variable and everything works nicely
b.setxy(4,4)

# This throws an exception, since self is undefined
a(4,4)


Best,

   -Nikolaus

-- 
 »It is not worth an intelligent man's time to be in the majority.
  By definition, there are already enough people to do that.«
                                                         -J.H. Hardy

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C




More information about the Python-list mailing list