4 things you might not know about Python functions

Source: Internet
Author: User
Tags closure function definition variable scope

About the definition of the function here, I prefer to imagine that the function is a black box, I need to get something directly into it, such as I want to understand the Python function, then directly Baidu search Python function, Baidu search will show me the relevant contents of the Python function, Baidu Search here is a function, I do not care how it is implemented internally, of course, if you write a function, you will have to consider a lot of things, the following say 4 things You may not know:

  1. Function high-force style use

  The essence of a function is an object, similar to a variable, that, when declaring a variable, generates a memory address to store the variable, as in the following code:

a=12345B=aprint('A's memory address is:%S\NB's memory address is:%s'%(ID (a), id (b ))# run Result:#  A memory address is: 31187568#  B memory address is: 31187568

Will find that when declaring variable a, open a memory address to save a variable, and then declare the variable b=a, you can see the memory address of A and B is the same, that is, A and B are points to the memory address of the content. So, in fact, the function is the same reason, declaring the function when the opening of a memory address to save the function content, the code is as follows:

def A ():     return b=aprint('A's memory address is:%S\NB's memory address is:%s'%(ID (a), id (b)))  # run Result:#  A memory address is: 2147864#  B memory address is: 2147864

You can see the function in the declaration, the memory works the same, so that in the call function, you can change the function of the object, that is, to change the name, if you think in the call function, change a high force lattice name to run is I want to say the high force style with words, please look down, my iron.

defPlay ():Print('go out the waves')defstudy ():Print('Study Hard') whileTrue:choice=input ('Please enter your choice: 1 for the wave, 2 for good study \ n')    ifchoice=='1': Play () Break    elifchoice==' 2': Study () Break    Else:        Print('Please enter the correct choice! ')        Continue

At this time the general function call, when the user input selection, call the corresponding function name, but so, each time to write the function of the call, if the options are many, in the time of writing is more troublesome, the following is the improved code (in dictionary form the option, function name), the call only need to pass key (choice Call value (function name) to:

defPlay ():Print('go out the waves')defstudy ():Print('Study Hard') Def_method={'1':p Lay,'2': Study} whileTrue:choice=input ('Please enter your choice: 1 for the wave, 2 for good study \ n')    ifchoice=='1' orchoice=='2': Def_method[choice] () Break    Else:        Print('Please enter the correct choice! ')        Continue

As above, the implementation of a key (choice) call value (function name) to meet the user input options call different functions, can be applied to such as user login, to determine the user role call different functions, according to the user's input selection call the corresponding function.

  2. function Variable scope

  Only modules, classes, and functions (Def, Lambda) in Python introduce new scopes, and other blocks of code (such as if/elif/else/, Try/except, For/while, and so on) do not introduce new scopes. That is, the variables defined within these statements can also be accessed externally. But here the function is the concept of variable scope, python scope has 4 kinds:

    • L (local) local scope
    • In functions outside of the E (enclosing) closure function
    • G (Global) scope
    • B (built-in) built-in scopes
x = Int (2.9)  # built- in scope g_count = 0  #  global scope def  outer ():    = 1  #  in functions outside the closure function    def  Inner ()        := 2  # Local Scope

To find the order of variables: local scope------global scope----built-in function in functions outside of the closure function, a layer of layers to find up, and so far. Here are two examples:

  The first example is a python exercise: how many lines of code are written in the statistics folder, including blank lines and comments, to count the number of lines of code, the number of empty lines, and the number of comment lines

Importoscomment_nums=0space_nums=0code_nums=0defcount (file,a,b,c): With open (file,'R', encoding='Utf-8') as F:arr=F.readlines () forIincharr:ifI.lstrip (). StartsWith ('#'): A+=1elifi=='\ n': b+=1Else: c+=1returnA,b,cfiles=os.listdir ('.') forIinchFiles:ifI.endswith ('. PY'): Comment_nums,space_nums,code_nums=count (i,comment_nums,space_nums,code_nums)Print('Comment has%s row \ n empty row has%s row \ n Code has%s row'% (comment_nums,space_nums,code_nums))

Notice that the function must return the corresponding statistic in the code above to modify the global variable: comment_nums,space_nums,code_nums; it's a bit cumbersome to write, and the following is the introduction of the global Variable Modification code:

Importoscomment_nums=0space_nums=0code_nums=0defcount (file):Globalcomment_numsGlobalspace_numsGlobalcode_nums with open (file,'R', encoding='Utf-8') as F:arr=F.readlines ()Print(arr) forIincharr:ifI.lstrip (). StartsWith ('#'): Comment_nums+=1elifi=='\ n': Space_nums+=1Else: code_nums+=1#print (a,b,c)    #return a,b,c,dCount'2. Log delete. py')Print(space_nums,code_nums,comment_nums)

  The second example , the nonlocal keyword, uses the global and nonlocal keywords when the internal scope wants to modify the variables of the outer scope.

def outer ():     = Ten    def  Inner ():        nonlocal num   #  nonlocal keyword declaration        num = 100        print(num)    inner ()    print(num) outer ()# Output Results 100100

If you want to modify a variable in a nested scope (enclosing scope, outer non-global scope), you need to nonlocal the keyword.

  3.lambda Anonymous functions

  Lambda can define an anonymous function, and the function defined by DEF must have a name.

  The function body of a lambda is a simple expression rather than a block of statements.

Basic usage is as follows

Lambda x, y, z:x + y + z  f (2, 3, 4)  

Equivalent to:

def return x + y + Z  

  

  4. Variable parameters

default parameter value: This allows the user to define some default values for the function's parameters. In this case, the function can be called with fewer parameters, and parameters not supplied when the function is called, Python uses the default supplied value as the parameter value.

(1) Only non-default positional parameter values are provided. In this example, the default parameter takes the defaults:

def Show_args (ARG, def_arg=1, def_arg2=2):      return"arg={}, def_arg={}, def_arg2={}". Format (ARG, Def_arg, DEF_ARG2) Show_args ("tranquility"   # output: ' Arg=tranquility, def_arg=1, def_arg2=2 '   

(2) Override some default parameter values with the provided values, including non-default positional parameters:

def Show_args (ARG, def_arg=1, def_arg2=2):      return"arg={}, def_arg={}, def_arg2={}". Format (ARG, Def_arg, DEF_ARG2) Show_args ("tranquility"  "to Houston")# output 'arg= Tranquility, Def_arg=to Houston, def_arg2=2'

(3) Provide values for all parameters that can be overridden by default parameter values:

defShow_args (ARG, def_arg=1, def_arg2=2):      return "arg={}, def_arg={}, def_arg2={}". Format (ARG, Def_arg, DEF_ARG2) Show_args ("Tranquility","To Houston","The Eagle has landed")#Output'arg=tranquility, Def_arg=to Houston, Def_arg2=the Eagle has landed'

  arbitrary list of parameters: Python also supports the definition of a function that can accept any number of parameters passed as a tuple, an example in the Python tutorial is as follows:

defWrite_multiple_items (file, separator, *args): File.write (Separator.join (args)) F= Open ("Test.txt","WB") Write_multiple_items (F," "," One"," Both","three"," Four","Five")#The above parameters, one, two, three, four, and five, are bundled together to form a tuple that can be accessed by using the parameter args .

  Keyword parameter: Use the keyword parameter in the form of "Kwarg=value" to call the function. Where Kwarg refers to the name of the parameter used in the function definition. Take the example of a function defined below that contains default and non-default parameters:

  

defShow_args (ARG, def_arg=1):       return "arg={}, def_arg={}". Format (ARG, def_arg) Show_args (Arg="Test", def_arg=3) Show_args (test) Show_args (Arg="Test") Show_args ("Test"-R)#in a function call, the keyword argument must not be earlier than the non-keyword argument, so the following call fails:Show_args (def_arg=4)#A function cannot provide a duplicate value for a parameter, so the following method of invocation is illegal:Show_args ("Test", arg="Testing")

In the example above, the parameter arg is the positional parameter, so the value "test" is assigned to it. Attempting to assign it again to the keyword arg means trying multiple assignments, which is illegal.

All keyword arguments passed must match one of the parameters accepted by the function, and the order of the keywords containing the non-optional arguments is not important, so the following change in the order of the arguments is legal:

Show_args (def_arg="testing", arg="test")

After the call, we welcome feedback and insufficient supplementary.

4 things you might not know about Python functions

Related Article

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.