cls & self
Diez B. Roggisch
deets at nospam.web.de
Fri Jul 27 06:50:43 EDT 2007
james_027 schrieb:
> 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
More information about the Python-list
mailing list