Reputation: 5440
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
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