擅长:python、mysql、java
<p>如果您使用的是Python2.6或更高版本,则可以使用类装饰器,可能类似于这样(警告:未测试的代码)。</p>
<pre><code>def class_decorator(cls):
for name, method in cls.__dict__.iteritems():
if hasattr(method, "use_class"):
# do something with the method and class
print name, cls
return cls
def method_decorator(view):
# mark the method as something that requires view's class
view.use_class = True
return view
@class_decorator
class ModelA(object):
@method_decorator
def a_method(self):
# do some stuff
pass
</code></pre>
<p>方法decorator通过添加一个“use_class”属性将该方法标记为感兴趣的方法-函数和方法也是对象,因此可以将其他元数据附加到它们。</p>
<p>创建类之后,类装饰器将遍历所有方法,并对已标记的方法执行所需的任何操作。</p>
<p>如果您希望所有的方法都受到影响,那么您可以省略方法decorator,而只使用类decorator。</p>