Method objects question

Greg Ewing greg.ewing at compaq.com
Wed Nov 24 04:51:28 EST 1999


Ben Caradoc-Davies wrote:
> 
> Why not convert both cases to method objects? 

Because most of the time most people *don't* want that to happen.

Usually when one plugs a function into an instance, it's so
that the instance can invoke some operation that's unrelated
to that instance, and the function being plugged in knows
nothing about the object it's being plugged into.

For example, in a GUI you might want to plug a method of
a Dialog subclass instance into a Button instance as a callback.
The callback wants access to the Dialog's instance variables,
not the Button's.

Then there's the case where you're just using an instance
variable as a storage place for something which happens to
be a function. The instance is never going to call the function,
just pass it on to something else. It would be highly annoying
if this were to mutate the function into a method!

What's worse, if you're writing general code which needs to
deal with any type of data, you don't even know whether a given
assignment to an instance variable is going to assign a function
or not. You'd have to wrap every piece of data that went into
any instance variable in a list or something, just on the offchance
that it was a function, to protect it from being mutated. I
don't know about you, but I would find that totally unacceptable.

If you really want to add a method to an individual instance,
there are ways of doing it. For instance, you could create a new 
subclass of the object's  __class__ on the fly, add the method to 
that, and change the object's __class__ to the new class.

A less hacky but slower way would be to define a callable object
class that emulates the behaviour of a bound-method object.

For that matter, you could probably use the 'new' module to create a
genuine bound-method object bound to the instance in question.

Greg




More information about the Python-list mailing list