python's OOP question

George Sakkis george.sakkis at
Mon Oct 16 07:31:24 CEST 2006

neoedmund wrote:

> python use multiple inheritance.
> but "inheritance" means you must inherite all methods from super type.
> now i just need "some" methods from one type and "some" methods from
> other types,
> to build the new type.
> Do you think this way is more flexible than tranditional inheritance?

The following does the trick:

from types import MethodType

def addMethod(meth, obj):
    f = meth.im_func
    setattr(obj, f.__name__, MethodType(f,obj))

def test1():
    addMethod(C2.m, C3)
    addMethod(C1.v, C3)
    o = C3()

The same works as is on modifying individual instances, rather than
their class:

def test2():
    o = C3()
    addMethod(C2.m, o)
    addMethod(C1.v, o)
    # raises AttributeError
    # C3().m()


More information about the Python-list mailing list