Multiple ways to define a class method in Python?

class, methods, python

Solution

`@classmethod` isn't the same as defining an instance method. Functions defined with `@classmethod` receive the class as the first argument, as opposed to an instance method which receives a specific instance. See the Python docs here for more information.

Problem

In Dive Into Python, Mark Pilgrim says that: When defining your class methods, you must explicitly list self as the first argument for each method He then gives a few examples of this in code: ``` def clear(self): self.data.clear() def copy(self): if self.__class__ is UserDict: return UserDict(self.data) import copy return copy.copy(self) ``` While going through some Python code online, I came across the `@classmethod` decorator. An example of that is: ``` class Logger: @classmethod def debug(msg): print "DEBUG: " + msg ``` (Notice that there is no `self` parameter in the `debug` function) Is there any difference in defining class methods using `self` as the first parameter and using the `@classmethod` decorator? If not, is one way of defining class methods more commonly used/preferred over another?

Original source

Related problems