python's OOP question
neoedmund
neoedmund at gmail.com
Mon Oct 16 02:02:55 EDT 2006
Oh, How great is the solution! ( though i don't know how it works. )
Thank you George.
George Sakkis wrote:
> 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()
> o.m()
>
> 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)
> o.m()
> # raises AttributeError
> # C3().m()
>
>
> George
More information about the Python-list
mailing list