Adding methods from one class to another, dynamically

Oltmans rolf.oltmans at gmail.com
Mon Feb 1 15:06:09 EST 2010


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)

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.

Many thanks and I look forward to any help.



More information about the Python-list mailing list