thoughts, ideas, code and other things...

Saturday, June 12, 2010

No more self everywhere

A lot of people complain about how they have to write "self" repetitively in their OO code in Python. Here is a neat trick that doesn't get you rid of "self" but lets you put another name for it -

>>> class Foo:
... def __init__(me):
... me.var = "Hola"
... def say(me):
... print me.var
>>> f = Foo()
>>> f.say()

Labels: ,


At June 28, 2010 at 10:57 AM , Anonymous Dheeraj said...

From Mark Pilgrim's 'Dive into Python'

"By convention, the first argument of any Python class method (the reference to the current instance) is called self. This argument fills the role of the reserved word this in C++ or Java, but self is not a reserved word in Python, merely a naming convention. Nonetheless, please don't call it anything but self; this is a very strong convention." :)

At June 29, 2010 at 1:13 PM , Blogger Abhishek Mishra said...

Figured out that it does cause problems with inheritance!


Post a Comment

Subscribe to Post Comments [Atom]

<< Home