你的意思是像添加裝飾到另一個模塊中的每個功能?你可以模擬與類:
class RequestsProxy(object):
def __init__(self):
self.special_sauce_decorator = special_sauce_indeed()
self._requests = __import__("requests")
def __getattr__(self, attrname):
val = getattr(self._requests, attrname)
if callable(val):
return self.special_sauce_decorator(val)
return val
用法示例:
>>> def special_sauce_indeed():
def decorator(f):
def wrapped(*args, **kwargs):
print 'wrapped'
return f(*args, **kwargs)
return wrapped
return decorator
>>> class OsProxy(object):
def __init__(self):
self.special_sauce_decorator = special_sauce_indeed()
self._requests = __import__("os")
def __getattr__(self, attrname):
val = getattr(self._requests, attrname)
if callable(val):
return self.special_sauce_decorator(val)
return val
>>> os = OsProxy()
>>> os.listdir(".")
wrapped
['DLLs', 'Doc', 'faiojerf.py', 'func_counter_test.py', 'include', 'inet_time.py', 'kcol.py', 'Lib', 'libs', 'LICENSE.txt', 'memoize_test.py', 'minpy.py', 'NEWS.txt', 'numpy-wininst.log', 'paren_test.py', 'PIL-wininst.log', 'psycopg2-wininst.log', 'python.exe', 'pythonw.exe', 'pywin32-wininst.log', 'README.txt', 'Removenumpy.exe', 'RemovePIL.exe', 'Removepsycopg2.exe', 'Removepywin32.exe', 'Removescipy.exe', 'Removesetuptools.exe', 'scipy-wininst.log', 'Scripts', 'setuptools-wininst.log', 'slots.py', 'so1.py', 'staticvar.py', 'summing.py', 'taojiwjiot.,py', 'tcl', 'templol.py', 'test.py', 'thunkify_test.py', 'TicketNumberGenerator.py', 'Tools', 'w9xpopen.exe', 'wordcount.py']
是的,我認爲這就是我的意思,謝謝。 – jon 2012-08-13 22:54:07
Neato!我不會做所有的異常檢查 - 'getattr'將會引發默認的異常(並且可以說'special_sauce_decorator'應該處理非可調用的事件)。 EAFP和所有這些=) – katrielalex 2012-08-13 23:01:07
歐洲魚類病理學家協會?哦,[gotcha](http://docs.python.org/glossary.html#term-eafp)。好點子 – Claudiu 2012-08-13 23:16:56