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

Terry Reedy tjreedy at udel.edu
Wed Aug 31 18:40:26 EDT 2011

On 8/31/2011 1:12 PM, Prasad, Ramit wrote:
>> 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()
 >> print(double(c),
>> C.double(c), c.double(), c.doub(c))

Above is 3.2 code. To be exactly equivalent with 2.x, you need
class C(object):

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

Right, because c.double() translates to C.double(c), and c.double(x)
translates to C.double(c,x), which is not valid.

>>>> print c.doub(c)
> 6
> It seems to me that if I add a function to the list of class
> attributes it will automatically wrap with "self"

When accessed via an instance of the class, the instance is 
automagically added as the first argument to be bound to the first 
parameter. The name 'self' is a convention, not a requirement.

> but adding it to
> the object directly will not wrap the function as a method. Can
> somebody explain why?

Someone else did. Not wrapping is normal, wrapping is a special case.

Terry Jan Reedy

More information about the Python-list mailing list