Why there is a parameter named "self" for classmethod function?
Chris Rebert
clp2 at rebertia.com
Wed May 6 22:55:57 EDT 2009
On Wed, May 6, 2009 at 7:49 PM, Jianchun Zhou <jianchun.zhou at gmail.com> wrote:
> Hi, ALL:
>
> I have a sample code as bellow:
>
> #!/usr/bin/env python
>
> class Hello:
> def __init__(self):
> print "Hello __init__"
> @classmethod
> def print_hello(self):
> print "hello"
>
> Hello.print_hello()
>
> If I move "self" parameter of print_hello away, this code fragment won't
> work.
>
> I am wondering when Hello.print_hello() executes, what value will "self" be
> asigned?
The class itself will be the value of self (hence the "class" in
"classmethod") in that case. For this reason, the parameter is
conventionally called "cls" rather than "self", to avoid confusion.
Cheers,
Chris
--
http://blog.rebertia.com
More information about the Python-list
mailing list