Python 5th Day

Source: Internet
Author: User

Further understanding of adorners

If you have the following logic:

def connect_db ():     Print ' Connect DB ' def close_db ():     Print ' Close DB ' def Query_user ():    connect_db ()    print'Query the user'      close_db ()

If we encapsulate the specific logic of query_user as a new function and then pass the new function into the query_data, then we need a different query method later, then we can encapsulate the new function.

def Query_user ():     Print ' query Some user ' def query_data (query):    connect_db ()    query ()    close_db ()

Well, Query_data is Query_user's decoration. But if we want to keep query_user, we need to call Query_data and return a function.

defQuery_user ():Print 'query Some user'defquery_data (query):"""define the adorner, return a function, wrapper the query with a wrapper"""    defwrapper (): connect_db () query () close_db ()returnwrapper#here call Query_data for actual decoration (note that decoration is a verb)Query_user =Query_data (Query_user)#call the decorated function Query_userQuery_user ()

The above is a complete adorner, the key point is that when calling Query_data, a wrapper function is returned, and this wrapper function performs some logic before and after the query function.

Note Query_user = Query_data (query_user) equals

# decorate with the @ call adorner @query_data def Query_user ():     Print ' query Some user '

@ Calling the adorner's syntax is not necessary, but just a syntactic sugar.

Multilayer Decorators
defDecorator1 (func):Print 'Inside Decorator1'    returnfuncdefDecorator2 (func):Print 'Inside Decorator2'    returnFunc@decorator1@decorator2defFunc1 (A, B, c):returnA, B, CPrintFunc1 (' All','Base','US')

In the above example, func1 is decorated with two decorators, so the decorator1 is decorated with a new function that is decorator2 decorated, so the output should be

Inside decorator2inside decorator1 ('all'base' ' US ')

Equivalent to:

func1 = Decorator1 (Decorator2 (FUNC1))
Module
  • 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 Mic Rosoft Windows INI files.
      • INI File Structure:
        1. A configuration file consists of sections, each led by a [section] header
        2. By default, section names is case sensitive but keys is not
        3. For example:
        4. [Simple Values]Key=valuespaces in Keys=allowedspaces in Values=allowed as wellspaces around the delimiter=Obviouslyyou can also use:to delimit keys from values[All Values is Strings]values like this:1000000or this:3.14159265359is they treated as numbers?: Nointegers,Floats and Booleans is held As:stringscan 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_valueempty String Value here=[can use comments]# like this;or this# By default @ an empty line.# Inline comments can is harmful because they prevent users# from using the delimit ing characters as parts of values.# that being said,This can is customized. [Sections Can Indented]Can_values_be_as_well=True does_that_mean_anything_special=False Purpose=formatting for readability multiline_values=Is handled just fine as long as they is indented deeper than the first line of a value # did I mention we can indent comments, too?
    • How to Read, Update and Delete Options

    • ImportConfigparserImportOSdefcreate_config (path):"""Create a config file"""Config=Configparser.configparser () config.add_section ("Settings") Config.set ("Settings","Font","Courier") Config.set ("Settings","font_size","Ten") Config.set ("Settings","Font_style","Normal") Config.set ("Settings","Font_info",               "You is using% (font) s at% (font_size) s PT") with open (path,"WB") as Config_file:config.write (Config_file)defget_config (path):"""Returns the Config object"""    if  notos.path.exists (path): create_config (path) config=Configparser.configparser () config.read (path)returnConfigdefget_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)returnvaluedefupdate_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)defdelete_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"," A") delete_setting (Path,"Settings","Font_style")
String formatting

In Python, the format used is consistent with the C language, implemented in%,

Common placeholders are:

%d: integer

%f: Floating point

%s: string

where formatted integers and floating-point numbers can also specify whether to complement 0 and the number of digits of integers and decimals:

' %2d-%02d ' % (3, 1)'  3-01'%.2f' % 3.1415926'  3.14'

To pass in as a dictionary:

% (name) s,% (age) d%{'name'"Gary" Age ': 30}

Once a placeholder is present and you want to pass in%, you need to use a percent, which is equivalent to escaping

              

Python 5th Day

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.