Adding methods from one class to another, dynamically
rolf.oltmans at gmail.com
Mon Feb 1 21:55:38 CET 2010
Thank you for your help, Chris. Looks like I can now attach methods to
class 'tee'. However, after attaching methods to 'tee' when I try to
run them using suite.run() I don't see any of the methods running, I'm
sorry but I've no clue what's failing this. Any insights will be
highly appreciated. Here is the sample code
print str(test) + ' succeeded'
print 'An error occured while running the test ' + str(test) +
' and error is = ' + str(err)
print str(test) + " failed with an error =" + str(err)
print 'first test'
print 'second test'
print 'third test'
r = result()
for name,func in inspect.getmembers(test,inspect.ismethod):
if name.find('test_')!= -1:
setattr(tee, name, new.instancemethod(func,None,tee))
suite = unittest.defaultTestLoader.loadTestsFromName('check.tee')
Then line suite.run(r) should have run the methods that we just
attached, but it's not. I must be missing something here. Please
On Feb 2, 1:25 am, Chris Rebert <c... at rebertia.com> wrote:
> On Mon, Feb 1, 2010 at 12:06 PM, Oltmans <rolf.oltm... 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
> 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))
> --http://blog.rebertia.com- Hide quoted text -
> - Show quoted text -
More information about the Python-list