Adding methods from one class to another, dynamically

Chris Rebert clp2 at rebertia.com
Mon Feb 1 15:25:49 EST 2010


On Mon, Feb 1, 2010 at 12:06 PM, Oltmans <rolf.oltmans at gmail.com> wrote:
> Hello Python gurus,
>
> I'm quite new when it comes to Python so I will appreciate any help.
> Here is what I'm trying to do. I've two classes like below
>
> import new
> import unittest
>
> class test(unittest.TestCase):
>    def test_first(self):
>        print 'first test'
>    def test_second(self):
>        print 'second test'
>    def test_third(self):
>        print 'third test'
>
> class tee(unittest.TestCase):
>    pass
>
> and I want to attach all test methods of 'test'(i.e. test_first(),
> test_second() and test_third()) class to 'tee' class. So I'm trying to
> do something like
>
> if __name__=="__main__":
>    for name,func in inspect.getmembers(test,inspect.ismethod):
>        if name.find('test_')!= -1:
>            tee.name = new.instancemethod(func,None,tee)

This ends up repeatedly assigning to the attribute "name" of tee; if
you check dir(tee), you'll see the string "name" as an entry. It does
*not* assign to the attribute named by the string in the variable
`name`.
You want setattr(): http://docs.python.org/library/functions.html#setattr
Assuming the rest of your code chunk is correct:

setattr(tee, name, new.instancemethod(func,None,tee))

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list