Asked By – marue
While integrating a Django app I have not used before, I found two different ways to define functions inside the class. The author seems to use them both distinctively and intentionally. The first one is the one that I myself use a lot:
class Dummy(object): def some_function(self, *args, **kwargs): # do something here # self is the class instance
The other one is the one I never use, mostly because I do not understand when and what to use it for:
class Dummy(object): @classmethod def some_function(cls, *args, **kwargs): # do something here # cls refers to what?
classmethod decorator in the python documentation says:
A class method receives the class as the implicit first argument, just
like an instance method receives the instance.
So I guess
cls refers to
Dummy itself (the
class, not the instance). I do not exactly understand why this exists, because I could always do this:
Is this just for the sake of clarity, or did I miss the most important part: spooky and fascinating things that couldn’t be done without it?
Now we will see solution for issue: When should I use @classmethod and when def method(self)?
Your guess is correct – you understand how
The why is that these methods can be called both on an instance OR on the class (in both cases, the class object will be passed as the first argument):
class Dummy(object): @classmethod def some_function(cls,*args,**kwargs): print cls #both of these will have exactly the same effect Dummy.some_function() Dummy().some_function()
On the use of these on instances: There are at least two main uses for calling a classmethod on an instance:
self.some_function()will call the version of
some_functionon the actual type of
self, rather than the class in which that call happens to appear (and won’t need attention if the class is renamed); and
- In cases where
some_functionis necessary to implement some protocol, but is useful to call on the class object alone.
The difference with
staticmethod: There is another way of defining methods that don’t access instance data, called
staticmethod. That creates a method which does not receive an implicit first argument at all; accordingly it won’t be passed any information about the instance or class on which it was called.
In : class Foo(object): some_static = staticmethod(lambda x: x+1) In : Foo.some_static(1) Out: 2 In : Foo().some_static(1) Out: 2 In : class Bar(Foo): some_static = staticmethod(lambda x: x*2) In : Bar.some_static(1) Out: 2 In : Bar().some_static(1) Out: 2
The main use I’ve found for it is to adapt an existing function (which doesn’t expect to receive a
self) to be a method on a class (or object).
This question is answered By – Marcin
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0