我在几个例子中注意到我看到这样的事情:
# Comments explaining code i think
@innerclass
Run Code Online (Sandbox Code Playgroud)
要么:
def foo():
"""
Basic Doc String
"""
@classmethod
Run Code Online (Sandbox Code Playgroud)
谷歌搜索并没有让我走得太远,只是对这是什么的一般定义.另外我在python文档中找不到任何东西.
这些怎么办?
Abh*_*pta 23
他们被称为装饰者.它们是应用于其他功能的功能.这是我对类似问题的回答的副本.
Python装饰器为另一个函数添加了额外的功能.斜体装饰器可能就像
def makeitalic(fn):
def newFunc():
return "<i>" + fn() + "</i>"
return newFunc
Run Code Online (Sandbox Code Playgroud)
请注意,函数是在函数内定义的.它基本上做的是用新定义的函数替换函数.例如,我有这门课
class foo:
def bar(self):
print "hi"
def foobar(self):
print "hi again"
Run Code Online (Sandbox Code Playgroud)
现在说,我希望两个函数在完成之后和之前打印"---".我可以在每个print语句之前和之后添加一个打印"---".但因为我不喜欢重复自己,我会做一个装饰
def addDashes(fn): # notice it takes a function as an argument
def newFunction(self): # define a new function
print "---"
fn(self) # call the original function
print "---"
return newFunction
# Return the newly defined function - it will "replace" the original
Run Code Online (Sandbox Code Playgroud)
所以现在我可以改变我的课程
class foo:
@addDashes
def bar(self):
print "hi"
@addDashes
def foobar(self):
print "hi again"
Run Code Online (Sandbox Code Playgroud)
有关装饰器的更多信息,请查看http://www.ibm.com/developerworks/linux/library/l-cpdecor.html
用
@function
def f():
pass
Run Code Online (Sandbox Code Playgroud)
你只需换function身边f()。function被称为装饰器。
它仅是以下语法糖:
def f():
pass
f=function(f)
Run Code Online (Sandbox Code Playgroud)