python's OOP question

neoedmund neoedmund at gmail.com
Mon Oct 16 02:00:45 EDT 2006


I found a dynamic way to inherite classes:

def MixIn(pyClass, mixInClass):
    if mixInClass not in pyClass.__bases__:
        pyClass.__bases__ += (mixInClass,)

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

"expected aaa"

neoedmund wrote:
> thank you, Kay.
>
> But i need a "dynamic" way. Say i have a existing class, and add some
> method from other class into it.
>
>
> Kay Schluehr wrote:
> > neoedmund wrote:
> > > There's a program, it's result is "unexpected aaa", i want it to be
> > > "expected aaa". how to make it work?
> > >
> > > [code]
> > >
> > > class C1(object):
> > > 	def v(self, o):
> > > 		return "expected "+o
> > >
> > > class C2(object):
> > > 	def v(self, o):
> > > 		return "unexpected "+o
> > > 	def m(self):
> > > 		print self.v("aaa")
> > >
> > > class C3(object):
> > > 	def nothing(self):
> > > 		pass
> > >
> > > def test1():
> > > 	o = C3()
> > > 	setattr(o,"m",C2().m)
> > > 	setattr(o,"v",C1().v)
> > > 	o.m()
> > >
> > > test1()
> > >
> > > [/code]
> >
> > class C3(C1, C2):pass
> >
> > >>> C3.mro()  # shows method resolution order
> > [<class '__main__.C3'>, <class '__main__.C1'>, <class '__main__.C2'>,
> > <type 'object'>]
> > 
> > >>> o = C3()
> > >>> o.m()
> > expected aaa




More information about the Python-list mailing list