Why do class methods always need 'self' as the first parameter?

Prasad, Ramit ramit.prasad at jpmorgan.com
Wed Aug 31 19:12:48 CEST 2011

>def double(obj): return 2*obj.value
>class C:
>     def __init__(self, val):
>         self.value = val
>c = C(3)
>C.double = double
>c.doub = double
># not c.double as that would mask access to C.double in c.double() below
>print(double(c), C.double(c), c.double(), c.doub(c))

Sorry if I get some of the following terminology wrong, I get a bit confused on Python terms. I hope the following is still coherent. (Is there a dictionary of Python terminology?)

Given the above example I get this
>>> print c.double(c)
TypeError: double() takes exactly 1 argument (2 given)

>>> print c.doub(c)

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

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?


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

More information about the Python-list mailing list