进一步理解装饰器
如果有如下逻辑:
def connect_db(): print ‘connect db‘ def close_db(): print ‘close db‘ def query_user(): connect_db() print ‘query the user‘ close_db()
如果我们把 query_user 的具体逻辑再封装为一个新函数,然后将新函数传入 query_data, 那么以后再需要不同的查询方法,就再封装新的函数就可以了。
def query_user(): print ‘query some user‘ def query_data(query): connect_db() query() close_db()
那么,query_data 就是 query_user 的装饰。但是如果我们想保持 query_user 不动,就需要调用 query_data 的时候返回一个函数。
def query_user(): print ‘query some user‘ def query_data(query): """ 定义装饰器,返回一个函数,对query进行wrapper包装 """ def wrapper(): connect_db() query() close_db() return wrapper # 这里调用query_data进行实际装饰(注意装饰是动词) query_user = query_data(query_user) # 调用被装饰后的函数query_user query_user()
以上就是一个完整的装饰器了,关键点在于调用 query_data 的时候,返回了一个 wrapper 函数,而这个 wrapper 函数执行query 函数前后的一些逻辑。
注意 query_user = query_data(query_user) 等于
# 使用 @ 调用装饰器进行装饰 @query_data def query_user(): print ‘query some user‘
@ 调用装饰器的语法不是必须的,而只是一种语法糖。
多层装饰器
def decorator1(func): print ‘Inside decorator1‘ return func def decorator2(func): print ‘Inside decorator2‘ return func @decorator1 @decorator2 def func1(a, b, c): return a, b, c print func1(‘All‘, ‘base‘, ‘us‘)
以上例子中,func1 被两个装饰器装饰,那么 decorator1 装饰的是被 decorator2 装饰过的新函数,所以输出应该是
Inside decorator2 Inside decorator1 (‘All‘, ‘base‘, ‘us‘)
等价于:
func1 = decorator1(decorator2(func1))
模块
- configparser
- more details, see: https://docs.python.org/3/library/configparser.html
- the ConfigParser class implements a basic configuration language which provides a structure similar to what’s found in Microsoft Windows INI files.
- INI File Structure:
- A configuration file consists of sections, each led by a [section] header
- By default, section names are case sensitive but keys are not
- For example:
-
[Simple Values] key=value spaces in keys=allowed spaces in values=allowed as well spaces around the delimiter = obviously you can also use : to delimit keys from values [All Values Are Strings] values like this: 1000000 or this: 3.14159265359 are they treated as numbers? : no integers, floats and booleans are held as: strings can use the API to get converted values directly: true [Multiline Values] chorus: I‘m a lumberjack, and I‘m okay I sleep all night and I work all day [No Values] key_without_value empty string value here = [You can use comments] # like this ; or this # By default only in an empty line. # Inline comments can be harmful because they prevent users # from using the delimiting characters as parts of values. # That being said, this can be customized. [Sections Can Be Indented] can_values_be_as_well = True does_that_mean_anything_special = False purpose = formatting for readability multiline_values = are handled just fine as long as they are indented deeper than the first line of a value # Did I mention we can indent comments, too?
- INI File Structure:
- How to Read, Update and Delete Options
-
import ConfigParser import os def create_config(path): """ Create a config file """ config = ConfigParser.ConfigParser() config.add_section("Settings") config.set("Settings", "font", "Courier") config.set("Settings", "font_size", "10") config.set("Settings", "font_style", "Normal") config.set("Settings", "font_info", "You are using %(font)s at %(font_size)s pt") with open(path, "wb") as config_file: config.write(config_file) def get_config(path): """ Returns the config object """ if not os.path.exists(path): create_config(path) config = ConfigParser.ConfigParser() config.read(path) return config def get_setting(path, section, setting): """ Print out a setting """ config = get_config(path) value = config.get(section, setting) print "{section} {setting} is {value}".format( section=section, setting=setting, value=value) return value def update_setting(path, section, setting, value): """ Update a setting """ config = get_config(path) config.set(section, setting, value) with open(path, "wb") as config_file: config.write(config_file) def delete_setting(path, section, setting): """ Delete a setting """ config = get_config(path) config.remove_option(section, setting) with open(path, "wb") as config_file: config.write(config_file) #---------------------------------------------------------------------- if __name__ == "__main__": path = "settings.ini" font = get_setting(path, ‘Settings‘, ‘font‘) font_size = get_setting(path, ‘Settings‘, ‘font_size‘) update_setting(path, "Settings", "font_size", "12") delete_setting(path, "Settings", "font_style")
字符串格式化
在Python中,采用的格式化方式和C语言是一致的,用%实现,
常见的占位符有:
%d: 整数
%f: 浮点数
%s: 字符串
其中,格式化整数和浮点数还可以指定是否补0和整数与小数的位数:
>>> ‘%2d-%02d‘ % (3, 1) ‘ 3-01‘ >>> ‘%.2f‘ % 3.1415926 ‘3.14‘
以字典形式传入:
%(name)s, %(age)d %{‘name‘: ‘gary‘, ‘age‘: 30}
一旦出现占位符,再想传入%,需要使用%%,相当于转义
时间: 2024-10-05 17:27:58