new.instancemethod questions

Mel mwilson at the-wire.com
Fri Jan 30 04:38:37 CET 2009


schickb wrote:

> I'd like to add bound functions to instances, and found the
> instancemethod function in the new module. A few questions:
> 
> 1. Why is instancemethod even needed? Its counter-intuitive (to me at
> least) that assigning a function to a class results in bound functions
> its instances, while assigning directly to instances does not create a
> bound function. So why doesn't assigning a function to an instance
> attribute result in a function bound to that instance?

If I understand you correctly, rebinding to the instance would break code
like:

myfakefile.write = sys.stdout.write

where the intent would be to redirect any output through myfakefile straight
to sys.stdout.  The code for the sys.stdout.write function would never find
the attributes it needed in the instance of myfakefile.  To do this,
methods have to stay bound to their proper instances.

        Mel.




More information about the Python-list mailing list