小编Bob*_*ang的帖子

如何在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 Code Online (Sandbox Code Playgroud)

运行上面的代码,结果是:

Finding files... …
Run Code Online (Sandbox Code Playgroud)

python closures scope class decorator

6
推荐指数
1
解决办法
749
查看次数

标签 统计

class ×1

closures ×1

decorator ×1

python ×1

scope ×1