1

装饰器

 2 years ago
source link: https://www.hi-roy.com/posts/%E8%A3%85%E9%A5%B0%E5%99%A8/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

装饰器 - Hi~Roy!

2013-11-01

装饰器的基础是 python 中函数也是对象,可以进行传递,可以在函数内部定义新的函数(函数内部的函数无法被单独调用)。 http://www.codecho.com/understanding-python-decorators/

# 装饰器makebold用于转换为粗体
def makebold(fn):
    # 结果返回该函数
    def wrapper():
        # 插入一些执行前后的代码
        return "<b>" + fn() + "</b>"
    return wrapper
# 装饰器makeitalic用于转换为斜体
def makeitalic(fn):
    # 结果返回该函数
    def wrapper():
        # 插入一些执行前后的代码
        return "<i>" + fn() + "</i>"
    return wrapper
@makebold
@makeitalic    #注意顺序很重要!!!!!
def say():
    return "hello"
print say()
#输出: <b><i>hello</i></b>
# 等同于
def say():
    return "hello"
say = makebold(makeitalic(say))
print say()
#输出: <b><i>hello</i></b>
Roy avatar
About Roy
野生程序猿,略懂Python,略懂Golang,略懂云计算,略懂大数据,略懂拳击游泳钓鱼,略懂钢琴吉他摄影。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK