python 装饰器有关的问题

LaoLiulaoliu 2011-12-24 01:17:18
1.装饰器问题。我注释掉的那一行代码,添加上也可以正常执行。原程序是有这一行的,我没懂所以注释掉了。句法:装饰器包装函数.装饰器函数 = {} (fmemo.memo = table)

def memo(f):
"Memoize function f."
table = {}
def fmemo(*args):
if args not in table:
table[args] = f(*args)
return table[args]
## fmemo.memo = table
return fmemo

@memo
def segment(text):
"Return a list of words that is the best segmentation of text."
if not text: return []
candidates = ([first]+segment(rem) for first,rem in splits(text))
return max(candidates, key=Pwords)



其实不用管代码逻辑,只要看看语法就好。问题感觉从来没接触过,谢谢。
...全文
97 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
LaoLiulaoliu 2011-12-26
  • 打赏
  • 举报
回复
楼上太强了,对python文档这么熟悉
angel_su 2011-12-25
  • 打赏
  • 举报
回复
看看文档有关language reference 3.1节提到:
...
Function objects also support getting and setting arbitrary attributes, which can be used, for example, to attach metadata to functions. Regular attribute dot-notation is used to get and set such attributes. Note that the current implementation only supports function attributes on user-defined functions. Function attributes on built-in functions may be supported in the future.
...
LaoLiulaoliu 2011-12-25
  • 打赏
  • 举报
回复
测试了一下,就是楼上说的这个意思。不知道哪里可以找到这个语法的文档,谢谢。
angel_su 2011-12-24
  • 打赏
  • 举报
回复
貌似就只是加个属性记住table,那么后面代码里,你可以用segment.momo来读取这个table
iambic 2011-12-24
  • 打赏
  • 举报
回复
什么问题?

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧