Monday, April 18, 2011

Python: Adding New Methods to an Instance

It's easy to dynamically add new methods to a class in Python, but all my attempts to add new methods directly to an instance had always involved hacks. When I discovered that Ruby had syntax to add methods directly to an instance, my curiosity in the subject was rekindled. Fortunately, someone pointed me to this blog post that shows how.

Why should you care? Most of the time, you shouldn't. You might want to use this trick if you were trying to do something like JavaScript's prototypal-based inheritance system. In my case, I think I was trying to do some funky monkey patching where I only wanted to monkey patch a particular instance instead of the class as a whole. Anyway, even if I can't come up with a good use case, I'm still glad I know how to do it ;)


Anonymous said...

This problem can be solved in more clean way If you take in account that functions are descriptors: = foo.__get__(instance, instance.__class__)

I recommend to read Python Attributes and methods.

Shannon -jj Behrens said...

Interesting. Thanks. Although, I don't understand why that's more clean.