467,118 Members | 991 Online
Bytes | Developer Community
Ask Question

Home New Posts Topics Members FAQ

Post your question to a community of 467,118 developers. It's quick & easy.

The need to put "self" in every method

Hi,

i was just wondering about the need to put "self" as the first
parameter in every method a class has because, if it's always needed,
why the obligation to write it? couldn't it be implicit?

Or is it a special reason for this being this way?

Thanks.

Jul 19 '05 #1
  • viewed: 1902
Share:
26 Replies
Fernando M. wrote:
Hi,

i was just wondering about the need to put "self" as the first
parameter in every method a class has because, if it's always needed,
why the obligation to write it? couldn't it be implicit?

Or is it a special reason for this being this way?

Thanks.

The reason can be found in the output from the python statement "import
this". Explicit is better than implicit.

regards
Steve
--
Steve Holden +1 703 861 4237 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/

Jul 19 '05 #2
"Fernando M." <fe*****************@gmail.com> wrote in message
news:11*********************@g14g2000cwa.googlegro ups.com...
Hi,

i was just wondering about the need to put "self" as the first
parameter in every method a class has because, if it's always needed,
why the obligation to write it? couldn't it be implicit?

Or is it a special reason for this being this way?
There are two different issues.

1. If self was made a keyword, there would be no need for
it in the method header. However, that would be a major
incompabible change affecting almost every script in existance.
Also some people use other words than self. (It would,
by the way, result in a performance improvement.)

2. There's been some talk of making the '.' operator allow an
implied instance. I'm not sure what the status of this is.

These two are actually separate issues; either could be
done without the other.

John Roth
Thanks.


Jul 19 '05 #3
Fernando M. wrote:
i was just wondering about the need to put "self" as the first
parameter in every method a class has because, if it's always needed,
why the obligation to write it? couldn't it be implicit?


py> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
....
STeVe
Jul 19 '05 #4
On 31 May 2005 08:45:45 -0700, Fernando M.
<fe*****************@gmail.com> wrote:
i was just wondering about the need to put "self" as the first
parameter in every method a class has because, if it's always needed,
why the obligation to write it?


It doesn't need to be 'self'. You could use 'this', or 's', or whatever.

Of course, if you *don't* use 'self', you should expect an angly mob
with pitchforks and torches outside your castle.

--
Cheers,
Simon B,
si***@brunningonline.net,
http://www.brunningonline.net/simon/blog/
Jul 19 '05 #5
Fernando M. wrote:
i was just wondering about the need to put "self" as the first
parameter in every method a class has because, if it's always needed,
why the obligation to write it? couldn't it be implicit?

Or is it a special reason for this being this way?


Because it's not always needed. See staticmethod or classmethod.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
The basis of optimism is sheer terror.
-- Oscar Wilde
Jul 19 '05 #6
Fernando M. <fe*****************@gmail.com> wrote:
i was just wondering about the need to put "self" as the first
parameter in every method a class has because, if it's always needed,
why the obligation to write it? couldn't it be implicit?


Didn't this exact question get asked just a few days ago?

Anyway, the short answer is:

1) Yes, it's always needed.
2) It's part of the Python design philosophy that "explicit is better
than implicit".

Note that in languages like C++ where using "this->" is optional,
people invent their own conventions for keeping local and instance
variables distinct, like prepending m_ to member names (except that
different people do it different ways, so it's more confusing).

Jul 19 '05 #7
>>>>> "Fernando M." <fe*****************@gmail.com> (FM) wrote:
FM> Hi,
FM> i was just wondering about the need to put "self" as the first
FM> parameter in every method a class has because, if it's always needed,
FM> why the obligation to write it? couldn't it be implicit? FM> Or is it a special reason for this being this way?


There is.
Inside a method there are 3 kinds of identifiers:
- local ones e.g. parameters and local variables
- global ones (actually module-level)
- instance variables and methods

Because Python has no declarations there must be a different way to
indicate in which category an identifier falls. For globals it is done with
the 'global' keyword (which actually is a declaration), for instance
variables the dot notation (object.name) is used and the rest is local.
Therefore every instance variable or instance method must be used with the
dot notation, including the ones that belong to the object `itself'. Python
has chosen that you can use any identifier to indicate the instance, and
then obviously you must name it somewhere. It could have chosen to use a
fixed name, like 'this' in Java or C++. It could even have chosen to use a
keyword 'local' to indicate local ones and let instance ones be the
default. But if instance variable would be implicit, local ones should have
been explicit.
--
Piet van Oostrum <pi**@cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: pi**@vanoostrum.org
Jul 19 '05 #8
Simon Brunning wrote:
On 31 May 2005 08:45:45 -0700, Fernando M.
<fe*****************@gmail.com> wrote:
i was just wondering about the need to put "self" as the first
parameter in every method a class has because, if it's always needed,
why the obligation to write it?

It doesn't need to be 'self'. You could use 'this', or 's', or whatever.

Of course, if you *don't* use 'self', you should expect an angly mob
with pitchforks and torches outside your castle.


Wouldn't an angly mob be carrying fishing rods?
Jul 19 '05 #9
John Machin wrote:
Of course, if you *don't* use 'self', you should expect an angly mob
with pitchforks and torches outside your castle.


Wouldn't an angly mob be carrying fishing rods?


Well, I thought they would be carrying pitchfolks and tolches.
Jul 19 '05 #10
In article <ma**************************************@python.o rg>,
Carl Friedrich Bolz <cf****@gmx.de> wrote:
John Machin wrote:
Of course, if you *don't* use 'self', you should expect an angly mob
with pitchforks and torches outside your castle.


Wouldn't an angly mob be carrying fishing rods?


Well, I thought they would be carrying pitchfolks and tolches.


You sure that's not perchforks?
Jul 19 '05 #11
John Machin wrote:
Simon Brunning wrote:
Of course, if you *don't* use 'self', you should expect an angly mob
with pitchforks and torches outside your castle.


Wouldn't an angly mob be carrying fishing rods?


No, I rather think they'd be acutely obtuse, right?
Jul 19 '05 #12

Simon> Of course, if you *don't* use 'self', you should expect an angly
Simon> mob with pitchforks and torches outside your castle.

I take it an "angly mob" is a large group of stick figures? <wink>

Skip
Jul 19 '05 #13
Skip Montanaro wrote:
Simon> Of course, if you *don't* use 'self', you should expect an angly
Simon> mob with pitchforks and torches outside your castle.

I take it an "angly mob" is a large group of stick figures? <wink>

Skip


Yep -- straw men.
Jul 19 '05 #14
On Wed, 01 Jun 2005 08:45:08 +1000, John Machin <sj******@lexicon.net>
declaimed the following in comp.lang.python:

Wouldn't an angly mob be carrying fishing rods?
Neither... the underfed 'roos would be eating their way
through... <G>

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 19 '05 #15
[posted & e-mailed]

In article <wz************@ordesa.lan>,
Piet van Oostrum <pi**@cs.uu.nl> wrote:

There is.
Inside a method there are 3 kinds of identifiers:
- local ones e.g. parameters and local variables
- global ones (actually module-level)
- instance variables and methods

Because Python has no declarations there must be a different way to
indicate in which category an identifier falls. For globals it is done with
the 'global' keyword (which actually is a declaration), for instance
variables the dot notation (object.name) is used and the rest is local.
Therefore every instance variable or instance method must be used with the
dot notation, including the ones that belong to the object `itself'. Python
has chosen that you can use any identifier to indicate the instance, and
then obviously you must name it somewhere. It could have chosen to use a
fixed name, like 'this' in Java or C++. It could even have chosen to use a
keyword 'local' to indicate local ones and let instance ones be the
default. But if instance variable would be implicit, local ones should have
been explicit.


Any objection to swiping this for the FAQ? (Probably with some minor
edits.)
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"The only problem with Microsoft is they just have no taste." --Steve Jobs
Jul 19 '05 #16
On Tuesday 31 May 2005 11:52 am, Roy Smith wrote:
Note that in languages like C++ where using "this->" is optional,
people invent their own conventions for keeping local and instance
variables distinct, like prepending m_ to member names (except that
different people do it different ways, so it's more confusing).


I would call this the "real" answer. I am aesthetically annoyed by
code like:

Post.postRead()

or even

Post.read_post()

The dot is there for a reason -- it qualifies the variable with the
class it applies to. What is the point of qualifying it AGAIN in the
method name? When I notice this in my own code, I reduce such
stuff to

Post.read()

IMHO, redundancy interferes with clarity, and one should use
the semantics of the language to describe the semantics of the
program --- that should make it easier for both Humans and
machines to understand the relationships in the code.

Using "self" is just like this, as indicated above: it replaces weird
naming conventions with a much more general one.

I've only ever replaced "self" with a different name once, and
that was when I was writing a vector math module -- I wanted
a more compact symbolic style, so I used "a":

def __add__(a,b):
return Vector((a.x+b.x), (a.y+b.y), (a.z+b.z))

or something like that. I still have twinges of guilt about it,
though, and I had to write a long note in the comments, apologizing
and rationalizing a lot. ;-)

I must say though, that as a newbie, I found this a lot easier
to get my head around than learning all the implicit variables
that Javascript introduces (e.g. "this", "prototype", etc).

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks http://www.anansispaceworks.com

Jul 19 '05 #17
Terry Hancock wrote:
def __add__(a,b):
return Vector((a.x+b.x), (a.y+b.y), (a.z+b.z))

or something like that. I still have twinges of guilt about it,
though, and I had to write a long note in the comments, apologizing
and rationalizing a lot. ;-)


Assigning self to a could have made it obvious:

def __add__(self, b):
a = self
return Vector((a.x+b.x), (a.y+b.y), (a.z+b.z))
--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
Jul 19 '05 #18
Aahz wrote:
[posted & e-mailed] Any objection to swiping this for the FAQ? (Probably with some minor
edits.)

I think it is missing the most important reason, that functions can act
as unbound methods.

--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
Jul 19 '05 #19
>>>>> aa**@pythoncraft.com (Aahz) (A) wrote:
A> [posted & e-mailed]
A> In article <wz************@ordesa.lan>,
A> Piet van Oostrum <pi**@cs.uu.nl> wrote:

There is.
Inside a method there are 3 kinds of identifiers:
- local ones e.g. parameters and local variables
- global ones (actually module-level)
- instance variables and methods

Because Python has no declarations there must be a different way to
indicate in which category an identifier falls. For globals it is done with
the 'global' keyword (which actually is a declaration), for instance
variables the dot notation (object.name) is used and the rest is local.
Therefore every instance variable or instance method must be used with the
dot notation, including the ones that belong to the object `itself'. Python
has chosen that you can use any identifier to indicate the instance, and
then obviously you must name it somewhere. It could have chosen to use a
fixed name, like 'this' in Java or C++. It could even have chosen to use a
keyword 'local' to indicate local ones and let instance ones be the
default. But if instance variable would be implicit, local ones should have
been explicit.
A> Any objection to swiping this for the FAQ? (Probably with some minor
A> edits.)


No.
The global/local stuff needs a bit more nuance (assignments in the method
being the criterium).
--
Piet van Oostrum <pi**@cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: pi**@vanoostrum.org
Jul 19 '05 #20
Explicit is better than implicit.


import sarcasm

def whatAboutMyImplicitModuleMethod()

Jul 19 '05 #21
Fernando M. schrieb:
i was just wondering about the need to put "self" as the first
parameter in every method a class has because, if it's always needed,
why the obligation to write it? couldn't it be implicit?

Or is it a special reason for this being this way?


See section 1.4.4 in http://www.python.org/doc/faq/general.html

--
-------------------------------------------------------------------
Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
-------------------------------------------------------------------
Jul 19 '05 #22
Aahz schrieb:
Because Python has no declarations there must be a different way to
indicate in which category an identifier falls.
[...] Any objection to swiping this for the FAQ? (Probably with some minor
edits.)


There is already a 'self' section (1.4.4) in the official Python FAQ.
Looks like this has been forgotten. Perhaps it would be helpful to
create a short version of the FAQ with the top most frequently asked
questions/stumbling blocks/annoyances titled "top 10 things you always
wanted to know about Python and didn't dare to ask" and post it weekly
in this newsgroup :)

--
-------------------------------------------------------------------
Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
-------------------------------------------------------------------
Jul 19 '05 #23
In article <d7**********@swifty.westend.com>,
Peter Maas <pe***@somewhere.com> wrote:
Aahz schrieb:

Because Python has no declarations there must be a different way to
indicate in which category an identifier falls.

[...]
Any objection to swiping this for the FAQ? (Probably with some minor
edits.)


There is already a 'self' section (1.4.4) in the official Python FAQ.
Looks like this has been forgotten. Perhaps it would be helpful to
create a short version of the FAQ with the top most frequently asked
questions/stumbling blocks/annoyances titled "top 10 things you always
wanted to know about Python and didn't dare to ask" and post it weekly
in this newsgroup :)


Ahhh... I looked in the Programming FAQ, but not the General FAQ. I
still think that section could use some clarification based on Piet's
wording, but it's less urgent.
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"The only problem with Microsoft is they just have no taste." --Steve Jobs
Jul 19 '05 #24
Fernando M. wrote:
Hi,

i was just wondering about the need to put "self" as the first
parameter in every method a class has because, if it's always needed,
why the obligation to write it? couldn't it be implicit?

Or is it a special reason for this being this way?

Thanks.


Here's how I view it... (It may not be strictly correct, so corrections
are welcome.)

It helps to think of new style class's as code patterns or templates to
create class-instance objects. Since you don't know what the name of
the instance object is going to be when you write the class, a way to
refer to the contents of the not yet created object is needed.

Passing the class-instance reference as the first argument is how Python
gets a reference to the local name space of the method. You can then
use that name to access the other objects in the class-instance or to
create new objects in the class-instance from within the method without
knowing what the class-instance name is before hand.

Python doesn't pass the 'self' reference when a locally defined function
is called inside a class or method. By having to *explicitly* receive
the 'self' reference in the argument list, it is clear when the 'self'
reference is available for use and when it's not.

Cheers,
_Ron_Adam
Jul 19 '05 #25
In article <wz************@ordesa.lan>,
Piet van Oostrum <pi**@cs.uu.nl> wrote:
aa**@pythoncraft.com (Aahz) (A) wrote:

Any objection to swiping this for the FAQ? (Probably with some minor
edits.)


No.
The global/local stuff needs a bit more nuance (assignments in the method
being the criterium).


Done! Thanks for prodding the update.
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.
Jul 19 '05 #26
D H
Steve Holden wrote:
Fernando M. wrote:
Hi,

i was just wondering about the need to put "self" as the first
parameter in every method a class has because, if it's always needed,
why the obligation to write it? couldn't it be implicit?

Or is it a special reason for this being this way?

Thanks.

One reason is because of the dynamic nature of Python classes. You can
attach new methods to a class after it is instantiated, or remove
methods. The language boo (http://boo.codehaus.org/) has classes
defined at compile time, and there "self" is not needed at all. If you
want to use the duck typing features in boo, however, and re-implement
python-like dynamic classes that can have methods removed or added at
any time, then your methods need some kind of "self" parameter so they
can access the context of their class instance, because really there is
no special relationship between the methods and the class unless you
explicitly specify it.
The reason can be found in the output from the python statement "import
this". Explicit is better than implicit.


Like those invisible yet explicit scope indicators, tabs and spaces.
Jul 19 '05 #27

This discussion thread is closed

Replies have been disabled for this discussion.

By using this site, you agree to our Privacy Policy and Terms of Use.