Why do class methods always need 'self' as the first parameter?
ian.g.kelly at gmail.com
Wed Aug 31 23:52:48 CEST 2011
On Wed, Aug 31, 2011 at 11:12 AM, Prasad, Ramit
<ramit.prasad at jpmorgan.com> wrote:
> It seems to me that if I add a function to the list of class attributes it will automatically wrap with "self" but adding it to the object directly will not wrap the function as a method. Can somebody explain why? I would have thought that any function added to an object would be a method (unless decorated as a class method).
Because things stored on the class are generally viewed as part of the
class definition, whereas things stored on an instance are generally
viewed as data -- a function stored on an object instance is usually
just meant to be a function. Consider the following code:
def __init__(self, keyfunc):
self.keyfunc = keyfunc
def sort(self, item_list):
sorter = Sorter(lambda x: x.id)
If adding keyfunc as an attribute to the object wrapped it up as a
method, it would break, since the function is not expecting a "self"
More technically, because descriptors are only invoked when they're
stored on the class.
> Hmm, or does the decoration just tell Python not to turn an object's function into a method? I.e. Is the decorator basically just the syntactic sugar for doing the above?
If you mean the staticmethod decorator, yes, it pretty much just wraps
the function as a "staticmethod" instance to prevent it from being
wrapped into an ordinary method when it's accessed.
More information about the Python-list