cls & self

J

james_027

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
 
S

Stargaming

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
 
D

Diez B. Roggisch

james_027 said:
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?

cls and self are just names. And you most certainly haven't seen the
above, but this instead:

class A(object):
@classmethod
def dosomething(cls):
pass


The decorator "classmethod" makes a method of a class a class-method.
That means that it's not invoked like this

a = A()
a.dosomething()

but

A.dosomething()

instead. Common usage are e.g. factory methods. And because it is a
classmethod, it gets the class passed as first argument, not the instance.


Diez
 
C

Chris Mellon

cls and self are just names. And you most certainly haven't seen the
above, but this instead:

Quite likely he has seen this, except there followed many other lines and then
dosomething = classmethod(dosomething) at the end.

This disjoint between where it's declared (and looks like a method)
and where it's set to a classmethod was a primary factor behind the
decorator syntax, of course.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top