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

Ian Kelly ian.g.kelly at gmail.com
Thu Sep 1 10:26:53 EDT 2011


On Thu, Sep 1, 2011 at 6:45 AM, John Roth <johnroth1 at gmail.com> wrote:
> I personally consider this to be a wart. Some time ago I did an
> implementation analysis. The gist is that, if self and cls were made
> special variables that returned the current instance and class
> respectively, then the compiler could determine whether a function was
> an instance or class method. If it then marked the code object
> appropriately you could get rid of all of the wrappers and the
> attendant run-time overhead.

I don't see how you could get rid of the wrappers.  Methods would
still need to be bound, somehow, so that code like this will work:

methods = {}
for obj in objs:
    if obj.is_flagged:
        methods[obj.user_id] = obj.do_work
    else:
        methods[obj.user_id] = obj.do_other_work
# ...
methods[some_user_id]()

Without method wrappers, how does the interpreter figure out which
instance is bound to the method being called?

Cheers,
Ian



More information about the Python-list mailing list