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

Terry Reedy tjreedy at udel.edu
Wed Aug 31 18:30:59 CEST 2011


On 8/31/2011 10:35 AM, T. Goodchild wrote:

> But one of the things that bugs me is the requirement that all class
> methods have 'self' as their first parameter.  On a gut level, to me
> this seems to be at odds with Python’s dedication to simplicity.

Actually, it is a consequence of Python's dedication to simplicity. A 
method is simply a function that is an attribute of a class. (This is 
even clearer in Py 3.) Hence, there is no special syntax for methods.

Consider

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

-- 
Terry Jan Reedy





More information about the Python-list mailing list