Python 5th Day

进一步理解装饰器

如果有如下逻辑:

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:

        1. A configuration file consists of sections, each led by a [section] header
        2. By default, section names are case sensitive but keys are not
        3. For example:
        4. [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?            
    • 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

Python 5th Day的相关文章

python -> lambda与def的区别

lambda可以定义一个匿名函数,而def定义的函数必须有一个名字.这应该是lambda与def两者最大的区别. 与Javascript不同的是,python中匿名函数与非匿名函数需要使用不同的语法来定义.这是因为: lambda是一个expression,不是一个statement. lambda is an expression, not a statement. 因此lambda表达式可以出现在def无法出现的地方.比如list comprehension. lambda表达式可以匿名也可

python学习之那些由print引起的困惑

该文索所起之因:在练习列表的操作时,要输出一波操作后的列表,但是一直让本人耿耿于怀的时下边的这个现象: 红色框框里是字符串,黄色框框里是列表,同样是只对一个元素进行的操作,为啥输出时字符串是作为一个整体输出,而列表却输出了一个"None",什么情况?于是多次实验,不管是remove还是extent等等,都输出一个"None"."None""None""None"你就只会一个"None"吗

总会有一个是你需要的

http://www.shouce.ren/post/d/id/112300 黑客攻防实战入门与提高.pdfhttp://www.shouce.ren/post/d/id/112299 黑客入门新手特训.pdfhttp://www.shouce.ren/post/d/id/112298 黑客与设计-剖析设计之美的秘密(彩印).pdfhttp://www.shouce.ren/post/d/id/112297 鸟哥的LINUX私房菜:服务器架设篇 (第二版).pdfhttp://www.shouc

[it-ebooks]电子书列表

#### it-ebooks电子书质量不错,但搜索功能不是很好 #### 格式说明  [ ]中为年份      ||  前后是标题和副标题  #### [2014]: Learning Objective-C by Developing iPhone Games || Leverage Xcode and Objective-C to develop iPhone games http://it-ebooks.info/book/3544/ Learning Web App Developmen

python3 -> 函数注释 Function Annotations

Python 3.X新增加了一个特性(Feature),叫作函数注释 Function Annotations 它的用途虽然不是语法级别的硬性要求,但是顾名思义,它可做为函数额外的注释来用. Python中普通的函数定义如下: def func(a, b, c): return a + b + c >>> func(1, 2, 3) 6 添加了函数注释的函数会变成如下形式: def func(a: 'spam', b: (1, 10), c: float) -> int: retu

(转) [it-ebooks]电子书列表

[it-ebooks]电子书列表 [2014]: Learning Objective-C by Developing iPhone Games || Leverage Xcode and Objective-C to develop iPhone games http://it-ebooks.info/book/3544/Learning Web App Development || Build Quickly with Proven JavaScript Techniques http://

Python300篇电子书免费送

此电子书集合由猪哥整理,免费发布于微信公众号:裸睡的猪. 此电子书集合将持续更新,获取最新电子书集合请关注微信公众号:裸睡的猪,回复:电子书此电子书集合仅用作个人学习,请勿用于商业获利!!! 数据科学速查表 零起点Python机器学习快速入门 <深度学习入门:基于Python的理论与实现>高清中文版PDF+源代码 <Python深度学习>2018中文版pdf+英文版pdf+源代码 stanford machine learning Python语言程序设计2018版电子教案 Pyt

Python初学者的捷径[译]

下面列出的都是这些年总结的Python的有用的知识点和一些工具.希望对你有所帮助! 交换变量值 x = 6 y = 5 x, y = y, x print x >>> 5 print y >>> 6 内联if语句 print "Hello" if True else "World" >>> Hello 联接 nfc = ["Packers", "49ers"] afc =

Python初学者的捷径

下面列出的都是这些年总结的Python的有用的知识点和一些工具.希望对你有所帮助! 交换变量值 x = 6 y = 5 x, y = y, x print x >>> 5 print y >>> 6 内联if语句 print "Hello" if True else "World" >>> Hello 联接 nfc = ["Packers", "49ers"] afc =