• Python装饰器


    1.定义:在不修改源代码和调用方式的基础上给其增加新的功能,多个装饰器可以装饰在同一函数上

    1)无参装饰器

    def deco(func1):
    
        def wrapper():
    
            func1()  func1=func
    
            print('456789')
    
            return wrapper
    
    @deco
    
    def func():
    
        print('123456')
    
    func()
    

    @deco相当于在函数func前执行

    func = deco(func)func=wrapper

    2)有参装饰器

    def deco(func):
    
        def wrapper(name,age):
    
            func(name,age)   #func = func1
    
            print('add new function')
    
        return wrapper
    
     
    
    @deco   # func1 = deco(func1)
    
    def func1(name,age):
    
        print('my name is %s,my age is %s' % (name, age))
    
     
    
     
    
    func1 = deco(func1)    #func1 = wrapper
    
    func1()    #wrapper()
    
     
    
    func1('蒋介石',99)
    

     

    3)增加用户认证功能

    def login(func):
    
        def wrapper():
    
            username = input('username:')
    
            password = input('password:')
    
            if username == 'root' and password == 'root':
    
                func()
    
            else:
    
                print('用户名密码错误')
    
        return wrapper
    
    def index():
    
        print('welcome to home')
    
    index = login(index)
    
    index()
    

    2.ConfigParser模块

    ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。

    import configparser
    
    config = configparser.ConfigParser()
    
    config.read('a.txt',encoding='utf-8')

    1)列出所有标题

    data = config.sections()
    
    print(data)
    

    2)利用section写入key=value,修改某个option的值,如果不存在则会出创建

    config.set('base','name','http://www.baidu.com')
    
    config.write(open('a.txt','w'))

    3)列出所有的key

    data = config.options('base')
    
    print(data)

    4)利用seciton和option取value

    data = config.get('base','enabled')
    
    print(data)

    5)利用section取出所有的键值对

    data = config.items('base')
    
    print(data)

    6)判断文件中是否有section

    res = config.has_section('base1')
    
    print(res)
    

    7)判断section下是否有指定的option

    res = config.has_option('base','baseurl')
    
    print(res)

    8)删除option

    config.remove_option('base','name')
    
    config.write(open('a.txt','w'))

    9)删除secion(会把下面的key value全部删除)

    config.remove_section('centos7')
    
    config.write(open('a.txt','w')) 
  • 相关阅读:
    操作系统知识点_用户编程接口
    操作系统知识点_内存管理
    操作系统知识点_进程管理
    LintCode 二叉树的后序遍历
    LintCode 二叉树的最大深度
    LintCode 二叉树的中序遍历
    LintCode 二叉树的前序遍历
    LintCode 删除排序链表中的重复元素
    Lintcode 二分查找
    lintcode 空格替换
  • 原文地址:https://www.cnblogs.com/Agnostida-Trilobita/p/11047161.html
Copyright © 2020-2023  润新知