Add bound methods to instantiated objects in Python

In Python, as in other dynamic languages, you can add new methods to a class after it's been defined. To do this in Python, you define a function that takes self as its first parameter, then assign that function to an attribute of the class:

class C(object):
    pass # No methods... yet

def foo(self):
    print self = foo

When executing the final line, Python automagically wraps the function foo in an unbound method called foo, and assigns the unbound method to (You need to be aware of this if you ever try to assign a function to an attribute of a class and want to use it as just a function: in that case, you would need to put it inside a data structure instead or use to get at the original function.)

This principle is not at work when you are dealing with an instance of a class. If you assign a function to an attribute of an instance, it will not be converted into anything. The creation of a bound method must be done explicitly, like this:

import types
instance = C() = types.MethodType(foo, instance, instance.__class__)

In this example, invoking MethodType creates a new bound method object. Its parameters are a function, the instance to which the method should be bound, and the class (the last parameter could simply be C, but using instance.__class__ allows you to use this approach when you don't have a direct reference to the class.)

Prev: Basic Formencode usage pattern

Next: WSGI decorators considered inconvenient

Share this content


Avatar picture for bav 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 [Link to] There is awesome info about python type system internals.
Avatar picture for Smithd404 I've read some excellent stuff here. Definitely price bookmarking for revisiting. I surprise how much effort you place to create this type of great informative site. aekcdkgeafdbcbbe

Post Comment

All comments are personally reviewed and must be:

  • On-topic
  • Courteous
  • Not self-linking or spam
(Optional. This is your one self-link.)