我可能怀疑这对装饰器来说是一个很好的用例,但在这里:
import string
SelfClosing = object()
def escapeAttr(attr):
# WARNING: example only, security not guaranteed for any of these functions
return attr.replace('"', '\\"')
def tag(name, content='', **attributes):
# prepare attributes
for attr,value in attributes.items():
assert all(c.isalnum() for c in attr) # probably want to check xml spec
attrString = ' '.join('{}="{}"'.format(k,escapeAttr(v)) for k,v in attributes.items())
if not content==SelfClosing:
return '<{name} {attrs}>{content}</{name}>'.format(
name = name,
attrs = attrString,
content = content
)
else: # self-closing tag
return '<{name} {attrs}/>'
例子:
def makeBoldWrapper(**attributes):
def wrapWithBold(origFunc):
def composed(*args, **kw):
result = origFunc(*args, **kw)
postprocessed = tag('b', content=result, **attributes)
return postprocessed
return composed
return wrapWithBold
演示:
@makeBoldWrapper(attr1='1', attr2='2')
def helloWorld(text):
return text
>>> print( helloWorld('Hello, world!') )
<b attr2="2" attr1="1">Hello, world!</b>
装饰器的常见误解是参数(attr1=...)
是装饰器的参数@myDecorator
;事实并非如此。相反,函数调用的结果myDecoratorFactory(attr1=...)
被计算为someresult
并成为匿名装饰器@someresult
。因此,“带参数的装饰器”实际上是需要将装饰器作为值返回的装饰器工厂。