擅长:python、mysql、java
<p>扩展<code>__get__</code>方法。这可以概括为decorator-decorator。在</p>
<pre><code>class _MethodDecoratorAdaptor(object):
def __init__(self, decorator, func):
self.decorator = decorator
self.func = func
def __call__(self, *args, **kwargs):
return self.decorator(self.func)(*args, **kwargs)
def __get__(self, instance, owner):
return self.decorator(self.func.__get__(instance, owner))
def auto_adapt_to_methods(decorator):
"""Allows you to use the same decorator on methods and functions,
hiding the self argument from the decorator."""
def adapt(func):
return _MethodDecoratorAdaptor(decorator, func)
return adapt
</code></pre>
<p>这样,您就可以让您的装饰器自动适应它所使用的条件。在</p>
^{pr2}$
<p>请注意,包装器函数是在所有函数调用中调用的,所以不要在那里做任何昂贵的操作。在</p>
<p>装饰工的使用:</p>
<pre><code>class Foo(object):
@allowed('GET', 'POST')
def do(self, request):
print "Request %s on %s" % (request, self)
@allowed('GET')
def do(request):
print "Plain request %s" % request
Foo().do('GET') # Works
Foo().do('POST') # Raises
</code></pre>