Adding methods from one class to another, dynamically

Chris Rebert clp2 at
Mon Feb 1 21:25:49 CET 2010

On Mon, Feb 1, 2010 at 12:06 PM, Oltmans <rolf.oltmans at> 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:
>   = 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
You want setattr():
Assuming the rest of your code chunk is correct:

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


More information about the Python-list mailing list