Aamir
Aamir

Reputation: 5440

Multiple ways to define a class method in Python?

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?

Upvotes: 4

Views: 7286

Answers (2)

RParadox
RParadox

Reputation: 6851

self is not and will never will be implicit.

"self will not become implicit.

Having self be explicit is a good thing. It makes the code clear by removing ambiguity about how a variable resolves. It also makes the difference between functions and methods small."

http://www.python.org/dev/peps/pep-3099/

Upvotes: 0

Yuushi
Yuushi

Reputation: 26040

@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.

Upvotes: 7

Related Questions