Python basis - function acquaintance (b)

1, the meta-information to the function parameter increases

Write a function, and then want to add some additional information for the parameters of this function, so other users will be able to know exactly how this function should be used.

Use the function parameter annotation is a good idea, it should prompt the programmer how to correctly use this function. For example, the following have been annotated a function:

def add(x:int, y:int) -> int:
    return x + y

python interpreter does not add any semantics for these annotations. They are not the type of inspection, before the effect of annotated with no run-time and there is no gap. However, for those who read the source code would be helpful in terms of friends. Third party

These tools and frameworks might add semantic annotations. At the same time they will also appear in the document.

help(add)

Help on function add in module __main__:

add(x: int, y: int) -> int

Although any type of object can be used to annotate the function (e.g., number, string, object instances, etc.), but generally speaking the use of string class or better point.

Function annotations are stored only in the function of the  __annotations__ property. E.g:

add.__annotations__
{'x': int, 'y': int, 'return': int}

Notes to use there could be many, but their main purpose is documentation. Because python is not the type of statement, generally speaking just by reading the source code is difficult to know what kind of parameters should be passed to this function. At this moment

Use annotations can give programmers more tips, so you can use the function correctly.

2, there is a default function arguments

Define an optional parameter of the function is very simple, direct specify a default value to the parameter in the function definition, and put the parameter list of the last on the list.

If the default parameter is a modifiable container, such as a list, set or dictionaries can be used as the default value of None, as follows:

# Use a list as the default 
DEF from spam (A = B, None):
     IF B IS None: 
        B = [] 
    ...

If you do not want to provide a default value, but want to test only under certain default parameter passed in is not there, you can write like this:

_no_value = object()

def spam(a, b=_no_value):
    if b is _no_value:
        print('No b value supplied')
    ...

We tested this function:

from spam (. 1) >> No value B Supplied 
from spam ( 1,2) = A >>. 1, B = 2 
from spam ( . 1, None). 1 >> A =, B = None    # can be found to the transmission and not a value of None by value in both cases there is a difference

Note: The value of the default parameter assignment only once when the function was created.

x = 20
def spam(a,b=x):
    print(a,b)

spam(1)  >> 1,20

x = 30
spam(1)   >> 1,20

When we change the value of x when the default parameter values ​​are not affected, because when the function definition has identified its default value of.

Secondly, the parameter should be a default value of immutable objects, such as None, True, False, number or string. In particular, do not write code like this:

def spam(a,[]):
    pass

If it does so, when the default value is modified elsewhere you will encounter all kinds of trouble. These changes will affect the default when this function is called next. such as:

def spam(a,b=[])
    print(b)
    return b

x = spam(1)

>> []

x.append(10)

x = spam(1)

>>[10]

This result is not what we want, in order to avoid such an outcome, try the default value is set to None, and then check it in a function, the previous example is to do so when testing None value, is very operator important, is the key point of this operation, we often written as follows:

def spam(a, b=None):
    if not b:
        b=[]

The problem is that although written so None value indeed be treated as False, but there are other objects (such as a string of length zero, lists, tuples, dictionaries, etc.) will be treated as False. Therefore, the above code will be entered as a number of other mistake is not entered. such as:

from spam (. 1) # the OK 
X = [] 
from spam ( . 1 , X) # same as above, parameters can be freely changed 
from spam ( . 1 , 0) # number, immutable 
from spam ( . 1, '' ) # string, immutable Types of

3, anonymous functions to capture variable values

Look at the code following effects:

x = 10
a = lambda y : x+y

x = 20

b = lambda y : x+y

a(10)  >> 30
b(20)  >> 30

lambda expression x is a free variable, bind values ​​at run time, and not binding on the definition, which is the default value of the parameter is defined with a different function. Therefore, when calling the lambda expression, the value of x is the value at the time of execution. E.g:

x = 10
a(10)   >> 20

x = 20

b(10)  >> 30

If you want an anonymous function when it is declared to capture the value of that parameter values ​​can be defined as the default parameters can be, as follows:

x = 10
a = lambda y, x=x: x+y
x = 20
b = lambda y,x=x: x+y

a(10)  >> 20
b(10)  >> 30

By creating a lambda expression list in a loop or list derivation, and function can be expected to remember every iteration value when you define.

# Error writing 

A = [ the lambda X: X + n- for n- in Range (. 4 )] 

for F in A: 
    F (0) 
    Print (F (0))

The above are all written output 4, beginning with the example, the function is running, the value of n is the last value iteration.

Using the function in the form of a default value of the parameter, lambda when defining the function can be bound to a value.

a = [lambda x,n=n:x+n for n in range(4)]

for f in a:
    f(0)
    print(f(0))

----------------

Guess you like

Origin www.cnblogs.com/huiyichanmian/p/12103187.html