Why there is a parameter named "self" for classmethod function?

Kurt Symanzik kurt at kbsymanzik.org
Wed May 6 23:01:44 EDT 2009


Jianchun Zhou <jianchun.zhou at gmail.com> wrote on 2009-05-07 10:49:33 AM 
+0800
> 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 self variable above with be populated with a reference to the class, 
so it would be more appropriately named cls such as:

@classmethod
def print_hello(cls):
	print "hello"

But you might consider decorating the method as a static method instead 
since in your example you are not using the parameter at all.  A static 
method would not require a parameter.

@staticmethod
def print_hello():
	print "hello"

Kurt

-- 
Kurt Symanzik
kurt at kbsymanzik.org
Skype id: ksymanzik
http://kbsymanzik.org



More information about the Python-list mailing list