Python装饰器

时间:2019-06-18 19:46:32   收藏:0   阅读:93

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‘))

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!