zoukankan      html  css  js  c++  java
  • python 装饰器

    python装饰器(fuctional decorators)就是用于拓展原来函数功能的一种函数,目的是在不改变原函数名(或类名)的情况下,给函数增加新的功能。 

    1.函数作为参数值返回

    def hi(name="yasoob"):
        def greet():
            return "now you are in the greet() function"
     
        def welcome():
            return "now you are in the welcome() function"
     
        if name == "yasoob":
            return greet
        else:
            return welcome
     
    a = hi()
    print(a)
    #outputs: <function greet at 0x7f2143c01500>
     
    #上面清晰地展示了`a`现在指向到hi()函数中的greet()函数
    #现在试试这个
     
    print(a())
    #outputs: now you are in the greet() function

    这是因为当你把一对小括号放在后面,这个函数就会执行;然而如果你不放括号在它后面,那它可以被到处传递,并且可以赋值给别的变量而不去执行它。

    2.装饰器的应用——日志

    from functools import wraps
    def logit(func):
        @wraps(func)
        def with_logging(*args, **kwargs):
            print(func.__name__ + " was called")
            print('args = {}'.format(*args))
            return func(*args, **kwargs)
    
        return with_logging
    
    
    @logit
    def addition_func(x):
        """Do some math."""
        return x + x
    
    
    result = addition_func(4)
    print(result)

    3.带有参数的装饰器

    from functools import wraps
     
    def logit(logfile='out.log'):
        def logging_decorator(func):
            @wraps(func)
            def wrapped_function(*args, **kwargs):
                log_string = func.__name__ + " was called"
                print(log_string)
                # 打开logfile,并写入内容
                with open(logfile, 'a') as opened_file:
                    # 现在将日志打到指定的logfile
                    opened_file.write(log_string + '
    ')
                return func(*args, **kwargs)
            return wrapped_function
        return logging_decorator
     
    @logit()
    def myfunc1():
        pass
     
    myfunc1()
    # Output: myfunc1 was called
    # 现在一个叫做 out.log 的文件出现了,里面的内容就是上面的字符串
     
    @logit(logfile='func2.log')
    def myfunc2():
        pass
     
    myfunc2()
    # Output: myfunc2 was called
    # 现在一个叫做 func2.log 的文件出现了,里面的内容就是上面的字符串
  • 相关阅读:
    java 找不到或无法加载主类
    navicat connect error: Authentication plugin 'caching_sha2_password' cannot be loaded
    mysql command
    the diffirent between step into and step over (java)
    20181015
    Eclipse
    游戏2048源代码
    vue的生命周期
    简单快速了解Vue.js的开发流程
    C# 连接西门子PLC
  • 原文地址:https://www.cnblogs.com/AntonioSu/p/12125190.html
Copyright © 2011-2022 走看看