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'))
作者:球接子
如有侵权,请联系13126893950@163.com删除
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,并在文章页面明显位置给出原文连接,否则不予转载且保留追究法律责任的权利。
本博客已不再更新,文章已转移至作者网站 :http://www.asumimoe.com/

浙公网安备 33010602011771号