• python 装饰器学习(decorator)


    最近看到有个装饰器的例子,没看懂,

    #!/usr/bin/python
    class decorator(object):
        def __init__(self,f):
            print "initial decorator"
            f()
        def __call__(self):
            print "call decorator"
    @decorator
    def fun():
        print "in the fun"
    print "after "
    fun()

    从stackoverflow看到了浏览最多的关于python装饰器的文章,下面是这个文章的网址

    http://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python/1594484#1594484

    感觉写的挺好的,我自己也总结总结。

    问题是lz想写个装饰器:

    @makebold
    @makeitalic
    def say():
       return "Hello"

    有这样的输出:

    "<b><i>Hello</i></b>"

    看到最短的回复是:

    def makebold(f): 
        return lambda: "<b>" + f() + "</b>"
    def makeitalic(f): 
        return lambda: "<i>" + f() + "</i>"
    
    @makebold
    @makeitalic
    def say():
        return "Hello"
    
    print say()

    太经典了,

    最开始的例子,先写段代码:

    #de 就代表decorator吧,简单些O(∩_∩)O~,
    def de(f):
    def wr():
    print "before func"
    f()
    print "after func"
    return wr

    def func():
    print "this is func self"
    #先运行一遍代码
    func()
    #装饰函数
    de_func=de(func)
    #运行装饰了之后的函数
    de_func()
    #或者
    #装饰函数
    func=de(func)
    #运行装饰了之后的函数
    func()
    #或者
    de(func)()

    还有一处需要理解的就是类的__call__方法是在instance=classname()()(也可以写成instance=classname();instance())的时候调用的

    python 自己的装饰器就是:

    #还可以在函数定义之前加上@de
    @de
    def func1():
        print "**this is func self"
    func1()
    

    理解了上面之后文章开头的例子也可以写成这样

    class decorator(object):
        def __init__(self,f):
            print "initial decorator"
            f()
        def __call__(self):
            print "call decorator"
    # @decorator
    def fun():
        print "in the fun"
    fun=decorator(fun)
    print "after "
    fun()
    

    有仔细看了那篇文章,感觉受益匪浅,也是自己当初学的时候没好好听吧。

           

  • 相关阅读:
    XAF中实现Combox属性编辑(官方)
    XAF 支持多数据库
    XAF 如何使用复合主键和复合外键
    如何禁止双击ListView记录显示DetailView?
    XAF中主从列表模式下获取当前主对象实例
    使用一个非持久字段PersistentAlias
    XAF 如何将文件存储在文件系统中而不是数据库中
    XAF中如何制作弹出窗体选择数据到ListView列表
    XAF 如何用其他线程更新对象
    XPO中 聚合函数的使用(Count,Max,Sum,Min)
  • 原文地址:https://www.cnblogs.com/WisWang/p/5446545.html
Copyright © 2020-2023  润新知