Właśnie napisałem klasę dekorator jak poniżej, starał się dodać obsługę debugowania dla każdej metody w klasie docelowej:Jak napisać prawidłowy dekorator klas w języku Python?
import unittest
import inspect
def Debug(targetCls):
for name, func in inspect.getmembers(targetCls, inspect.ismethod):
def wrapper(*args, **kwargs):
print ("Start debug support for %s.%s()" % (targetCls.__name__, name));
result = func(*args, **kwargs)
return result
setattr(targetCls, name, wrapper)
return targetCls
@Debug
class MyTestClass:
def TestMethod1(self):
print 'TestMethod1'
def TestMethod2(self):
print 'TestMethod2'
class Test(unittest.TestCase):
def testName(self):
for name, func in inspect.getmembers(MyTestClass, inspect.ismethod):
print name, func
print '~~~~~~~~~~~~~~~~~~~~~~~~~~'
testCls = MyTestClass()
testCls.TestMethod1()
testCls.TestMethod2()
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
Run powyższym kodzie, wynik jest:
Finding files... done.
Importing test modules ... done.
TestMethod1 <unbound method MyTestClass.wrapper>
TestMethod2 <unbound method MyTestClass.wrapper>
~~~~~~~~~~~~~~~~~~~~~~~~~~
Start debug support for MyTestClass.TestMethod2()
TestMethod2
Start debug support for MyTestClass.TestMethod2()
TestMethod2
----------------------------------------------------------------------
Ran 1 test in 0.004s
OK
może się okazać, że "TestMethod2" wydrukowano dwukrotnie.
Czy jest problem? Czy moje zrozumienie jest właściwe dla dekoratora w pytonie?
Czy istnieje sposób obejścia tego problemu? BTW, nie chcę dodawać dekoratora do każdej metody w klasie.
Pozdrawiamy, @eryksun. Myślę, że to jest lepsze. – unutbu