4

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?

Aamir
  • 5,324
  • 2
  • 30
  • 47
  • 1
    `self` means reference to class instance. See http://stackoverflow.com/questions/38238/what-are-class-methods-in-python-for – Pavel Paulau Oct 21 '12 at 23:50

2 Answers2

7

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

Yuushi
  • 25,132
  • 7
  • 63
  • 81
  • Thanks! The sentence from the book makes a lot more sense now. I missed his point and thought he meant class methods (as in, static methods) where as he only meant methods defined inside a class. Hence, `self` is the reference to the instance of that class which obviously won't work when using `@classmethod` since you don't have an instance :) – Aamir Oct 21 '12 at 23:54
0

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/

RParadox
  • 6,393
  • 4
  • 23
  • 33