What is class method?

Medardo Rodriguez (Merchise Group) med.swl at gmail.com
Sun Aug 24 17:11:15 CEST 2008


On Sun, Aug 24, 2008 at 4:32 AM, Hussein B <hubaghdadi at gmail.com> wrote:
> I'm familiar with static method concept, but what is the class method?
> how it does differ from static method? when to use it?

"Class Methods" are related to the meta-class concept introduced since
the first beginning of OOP but not known enough so far.
If you are capable to reason (to model) using that concept, the you
will need "classmethod" decorator in Python.

"Static Methods" are global operations but are declared in the
name-space context of a class; so, they are not strictly methods.

In Python everything is an object, but functions declared in the
module scope not receive the instance of the module, so they are not
module methods, they are not methods, they are global functions that
are in the name-space context of the module in this case.

Methods always receive the instance as a special argument (usually
declared as self in Python). Classes (theoretically speaking) are also
objects (dual behavior).

Let's be explicit:

#<code>
class Test(object):
   def NormalMethod(self):
       print 'Normal:', self

   @staticmethod
   def StaticMethod(self=None):
       print 'Static:', self

   @classmethod
   def ClassMethod(self):
       print 'Class:', self

test = Test()
test.NormalMethod()
test.StaticMethod()
test.ClassMethod()   # the instance "test" is coerced to it's class to
call the method.
#</code>

Regards



More information about the Python-list mailing list