Adding methods from one class to another, dynamically

Carl Banks pavlovevidence at
Mon Feb 1 21:45:03 CET 2010

On Feb 1, 12:06 pm, Oltmans <rolf.oltm... 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.

Simplest way:

class tee(test):

To do it dynamically the following might work:

class tee(unittest.TestCase):

tee.__bases__ = (test,)
tee.__bases__ = (test2,) # dynamically reassign base

> 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)
> after doing above when I run this statement
> print dirs(tee)
> I don't see test_first(), test_second() and test_third() attached to
> class 'tee'. Any ideas, on how can I attach methods of class 'test' to
> class 'tee' dynamically? Any help is highly appreciated.

If you want to do it this way--and I recommend regular inheritance if
you can--this is how:

for x in dir(test):  # or inspect.getmembers
    if x.startswith('test_'):
        method = getattr(test,x)
        function = method.im_func

The business with method.im_func is because in Python 2.x the getattr
on a class will actually returns an unbound method, so you have to get
at the actual function object with im_func.  In Python 3 this is not

Carl Banks

More information about the Python-list mailing list