cls & self

Stargaming stargaming at gmail.com
Thu Jul 26 01:46:23 EDT 2007


On Thu, 26 Jul 2007 03:07:56 +0000, james_027 wrote:

> hi,
> 
> is cls & self the same thing?
> 
> I have seen something like
> 
> class A:
>     def dosomething(cls):
>        #doing something
> 
> How is cls & self differ? How is it use?
> 
> Thanks
> james

First, you have to understand that the choice of this name is *completely 
arbitrary*. You could call it self, cls, this, bogus, helloworld or 
whatsoever. The important thing is just: The first argument is (by 
default) the instance.

Amongst python developers, many things aren't enforced by the language 
(eg. implicit `this` referencing the instance, as in other languages) but 
by conventions. It's just way more convenient to call it `self` always. 
We call it `cls` when speaking about classmethods. Your method there 
might have been headed by a line containing ``@classmethod``.

See http://docs.python.org/lib/built-in-funcs.html#l2h-16 for classmethod 
and http://docs.python.org/tut/node11.html#SECTION0011400000000000000000 
for this conventional stuff (paragraph "Often, the first argument ...").

HTH,
Stargaming



More information about the Python-list mailing list