对Python装饰程序不熟悉,并试图理解以下代码的“流程”:
def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)
def p_decorate(func):
print "here's what's passed to p_decorate(func): %s" % func
def func_wrapper(name):
print "here's what's passed to the inner func_wrapper(name) function: %s" % name
return "<p>{0}</p>".format(func(name))
return func_wrapper
my_get_text = p_decorate(get_text("fruit"))
print my_get_text("GOODBYE")
my_get_text = p_decorate(get_text)
print my_get_text("veggies")
为什么print my_get_text("GOODBYE")
行得到TypeError: 'str' object is not callable
?你知道吗
如果我已经将get_text(name)
函数传递给了行中的p_decorate(func)
,即使我也给了get_text()
一个字符串“fruit”,为什么我不能用"GOODBYE"
重新分配传递给name
参数的内容呢?你知道吗
你必须这样定义
my_get_text
因为
p_decorate
需要一个函数作为参数,get_text("fruit")
是一个字符串,因为调用时get_text
会返回这个字符串。因此出现了错误。你知道吗这就是decorator所要做的,修改一个函数。如果将参数传递给函数,则会对其求值,结果(通常)与生成它的函数没有任何关联。你知道吗
相关问题 更多 >
编程相关推荐