Python function invocation and execution trivia

Source: Internet
Author: User

1. Symbol table

Executing a function introduces a new symbol table for the local variables of the function.

To be more exact,

All assignments in the function are stored in the local symbol table;

Instead, the variable reference finds the local symbol table first,

Then is the local symbol table of the upper function,

Then the global symbol table,

Finally, the built-in name table.

Therefore, global variables within a function cannot be directly assigned (unless named in a global statement), although they can be referenced.

2. Transfer value

The actual parameters of the function call introduce the local symbol table of the modulated function when the function is called;

So

parameter is passed using a value call

(The value here is always a reference to the object, not the value of the object.)

When one function calls another function,

A new local symbol table is created for the call.

The function definition introduces a function name within the current symbol table.

The type of the corresponding value of the function name is a user-defined function that the interpreter can recognize.

This value can be assigned to another name,

It can then be used as a function.

This is a generic renaming mechanism:

Parameter: The default value is calculated when a function definition in a domain is defined

Important Warning:

The default value is calculated only once.

This makes the default values different for lists, dictionaries, or instances of most classes.

For example

The following function accumulates the arguments passed to it during subsequent calls:

F(al=l. ) Append(aLf(1)F(2)F(3)  

This will print

[1][12][123]         

If you do not want the default values to be shared in subsequent calls,

You can write functions like this:

F(al=nonenonel.  Append(aL           

When the last formal parameter appears in the form of a **name ,

It receives a dictionary (see Map Type-dictionary),

The dictionary contains all the keyword parameters that do not appear in the formal parameter list.

It may also be used in combination with parameters in the form of *name (as described in the next section).

*name receives a parameter tuple that contains all the positional parameters that do not appear in the formal parameter list.

(*name must appear before **name .) )

For example

If we define such a function:

DefCheeseshop(Kind,*Arguments,**Keywords):Print"--Do you have any",Kind,"?"Print "--I ' m Sorry, we ' re all out of" kind for arg in arguments: print arg Span class= "K" >print  "-" * 40 keys  = sorted (keywords. Keys ()) for kw in keys : print kw ":" keywords[kw]       

It can be called this way:

Cheeseshop("Limburger" "It ' s very runny, sir." "It ' s really very, very runny, sir." shopkeeper=' Michael Palin 'client="John Cleese"sketch="Cheese Shop Sketch ")             

Of course it will print:

Limburger?--I ' m Sorry, we ' re all out of Limburgerit ' s very runny, sir. It ' s really very, very runny, sir.----------------------------------------Client:john Cleeseshopkeeper:michael Palins Ketch:cheese Shop Sketch

Note Before you print the keyword parameters,

By sorting the results of the keys () method of the keyword dictionary,

A list of keyword parameter names is generated;

If you do not do this,

The order of the printed parameters is undefined.

3. Differences in procedures and functions

If you have used other languages, you may be opposed to saying:

fib is not a function, but a process (subroutine),

Because it does not return any values.

In fact, a function without a return statement also returns a value, albeit a very boring value.

This value is called None(It is a built-in name).

If None is the only output, the interpreter will not normally print it out.

If you really want to see this value, you can use the print statement.

4. Parameter splitting

splitting of parameter lists

When the passed parameter is already a list or tuple,

The situation is in contrast to the previous

You're going to split these parameters,

Because a function call requires a separate positional parameter.

For example

The built-in range () function expects a separate start and stop parameters.

If they are not independent,

Use the *-operator to detach a parameter from a list or tuple when the function is called:

>>>
Range(36# Normal call with separate arguments[3, 4, 5][36]range( *args# arguments unpacked from a list[3, 4, 5]       

In the same way, you can use the * *-operation Foujian dictionary to pass the keyword parameters:

>>>
>>>DefParrot(Voltage,State=' A stiff ',Action=' Voom '):...Print"--this parrot wouldn ' t",Action,...Print"If you put",Voltage,"Volts through it.", ... print  "E ' s" state,  "!"  ... >>> d = { "voltage" :  "four million"  "state" :  "Bleedin ' demised"  "action" :  " Voom "}>>> parrot (**< span class= "n" >d) --this parrot wouldn ' t voom if you put a four million volts through it. E ' s bleedin ' demised!                

5.lambda Anonymous Small function

You can use the lambda keyword to create small anonymous functions.

The following function returns the and of its two parameters:

Lambda A, B: A + b.

A LAMBDA function can be used wherever a function object is needed.

In grammar, they are confined to a single expression only.

Semantically, they are just syntax sugars defined by normal functions.

Like nested function definitions, a lambda function can reference a variable from a containing range:

Make_incrementor(n):xn... make_incrementor(0) F(1) 

The example above uses a lambda expression to return a function.

Another use is to pass a small function as a parameter:

>>>
>>>Pairs=[(1 (2 Span class= "s" > "),  (3" Three '  (4 ' four ' )]>>> pairs. Sort (key=lambda pair : pair[1])  >>> pairs[(4, ' Four '), (1, ' One '), (3, ' three '), (2, ' one ')]   span>                 

6. Document String

The first line should always be a short, precise summary of the object's purpose. for simplicity, the name or type of the object should not be explicitly stated, as it can be learned in other ways (unless the name happens to be a verb describing the operation of the function). This line should start with a capital letter and end with a period.

If there are more rows in the document string, the second line should be blank, visually separating the summary from the remaining description. the following lines should be one or more paragraphs describing the object's calling convention, its side effects, and so on.

The Python interpreter does not remove indents from multiple lines of document strings, so tools that handle document strings when necessary should clear the indentation themselves. This can be achieved by using the following conventions. the first non-empty row string after the first line determines the amount of indentation for the entire document string. (We don't use the first line because it's usually close to the quotation marks at the beginning of the string and its indentation is not clear.) the spaces that are equal to the indentation at the beginning of all rows are filtered out. You should not indent fewer rows, but if they occur, all of their leading blanks should be removed. The length of the white space should be equal to the width of the Extended tab (8 spaces normally).

Here is an example of a multi-line document string:

>>>
My_function(): ...     "" Does nothing , but document it. ... No, really, it doesn ' t do anything. "" " pass... my_function.  __doc__ does nothing, but document it.  No, really, it doesn ' t do anything.            

Python function invocation and execution trivia

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.