# Python Learning notes-function Chapter

Source: Internet
Author: User

DefinedReturn single value
``def my_abs(x):    if x >= 0:        return x    else:        return -x``
Returns multiple values

Returns a multivalued value that returns a tuple

``import mathdef move(x, y, step, angle=0):    nx = x + step * math.cos(angle)    ny = y - step * math.sin(angle)    return nx, ny``
Null function
``def nop():    pass``
Specifying default parameters

The required parameters are before the default parameters. The default parameter needs to point to the immutable object (the default parameter value is computed when the function is defined)

``def power(x, n=2):    s = 1    while n > 0:        n = n - 1        s = s * x    return s``
Variable parameters
``def calc(*numbers):    sum = 0    for n in numbers:        sum = sum + n * n    return sum``

function methods that call variable arguments

``>>> calc(1, 2)5>>> calc()0>>> nums = [1, 2, 3]>>> calc(*nums)14``
Keyword parameters
``def person(name, age, **kw):    print ‘name:‘, name, ‘age:‘, age, ‘other:‘, kw``

Methods for calling keyword arguments

``>>> person(‘Michael‘, 30)name: Michael age: 30 other: {}>>> person(‘Bob‘, 35, city=‘Beijing‘)name: Bob age: 35 other: {‘city‘: ‘Beijing‘}>>> person(‘Adam‘, 45, gender=‘M‘, job=‘Engineer‘)name: Adam age: 45 other: {‘gender‘: ‘M‘, ‘job‘: ‘Engineer‘}>>> kw = {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}>>> person(‘Jack‘, 24, **kw)name: Jack age: 24 other: {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}``

Note:

• The order of the parameter definitions must be: required, default, variable, and keyword parameters.
• For any function, it can be called in a similar `func(*args, **kw)` manner, regardless of how its arguments are defined.
Recursive

If a function calls itself internally, the function is a recursive function.

Tail recursion

When the function returns, it calls itself, and the return statement cannot contain an expression.

Higher order functions
• A variable can point to a function (a function can be assigned a value to a variable)
• The function name is also a variable (other values can be assigned to the functional name)
• Functions can be used as parameters of functions (higher-order functions)
Map (func, list)

The map () function receives two parameters, one is a function, the other is a sequence, and map passes the incoming function to each element of the sequence sequentially, returning the result as a new list.

``>>> def f(x):...     return x * x...>>> map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])[1, 4, 9, 16, 25, 36, 49, 64, 81]``
Reduce (func_with_two_params, list)

Reduce functions a function in a sequence [X1, x2, x3 ...] , the function must receive two parameters, and reduce accumulates the result and the next element of the sequence.

``reduce(f, [x1, x2, x3, x4])#相当于：f(f(f(x1, x2), x3), x4)>>> def add(x, y):...     return x + y...>>> reduce(add, [1, 3, 5, 7, 9])25``
Filter (Func_return_bool, list)

The passed-in function is applied to each element sequentially, and then the element is persisted or discarded depending on whether the return value is true or false.

``def is_odd(n):    return n % 2 == 1filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])# 结果: [1, 5, 9, 15]``
Sorted

For two elements and, if considered, returns if considered, returns `x` `y` `x < y` `-1` `x == y` `0` If considered `x > y` , `1`

``>>> sorted([36, 5, 12, 9, 21])[5, 9, 12, 21, 36]``

Higher-order function usage

``def reversed_cmp(x, y):    if x > y:        return -1    if x < y:        return 1    return 0>>> sorted([36, 5, 12, 9, 21], reversed_cmp)[36, 21, 12, 9, 5]``
function as return value
``def lazy_sum(*args):    def sum():        ax = 0        for n in args:            ax = ax + n        return ax    return sum>>> f = lazy_sum(1, 3, 5, 7, 9)>>> f<function sum at 0x10452f668>>>> f()25``

Note: Each call `lazy_sum()` will return a new function, even if the same parameters are passed in.

Closed Package
``def count():    fs = []    for i in range(1, 4):        def f():             return i*i        fs.append(f)    return fsf1, f2, f3 = count()>>> f1()9>>> f2()9>>> f3()9``

The reason is that the loop was executed when Count was called, but it was `f()` not executed until it was called. So the return function does not refer to any loop variables, or to subsequent variables that change.

An anonymous function (lambda expression)
``lambda x: x * x``

Equivalent to:

``def f(x):    return x * x``

The keyword `lambda` represents an anonymous function, preceded by a colon, that `x` represents a function parameter.

anonymous function as return value
``def build(x, y):    return lambda: x * x + y * y``
Decorators (@func)

The way in which functions are dynamically added during code operation, called "adorners" (Decorator), Decorator is essentially a higher-order function that returns functions.

``def log(func):    def wrapper(*args, **kw):        print ‘call %s():‘ % func.__name__        return func(*args, **kw)    return wrapper@logdef now():    print ‘2013-12-25‘>>> now()call now():2013-12-25#相当于执行：now = log(now)``
``def log(text):    def decorator(func):        def wrapper(*args, **kw):            print ‘%s %s():‘ % (text, func.__name__)            return func(*args, **kw)        return wrapper    return decorator@log(‘execute‘)def now():    print ‘2013-12-25‘#执行结果>>> now()execute now():2013-12-25#相当于执行：>>> now = log(‘execute‘)(now)``

Anatomy: First executes `log(‘execute‘)` , returns a `decorator` function, then calls the returned function, the argument is a `now` function, the return value is ultimately a `wrapper` function.

`__name__`

Because the function `__name__` has changed, the code that relies on it will go wrong. So use `functools.wraps` .

``import functoolsdef log(func):    @functools.wraps(func)    def wrapper(*args, **kw):        print ‘call %s():‘ % func.__name__        return func(*args, **kw)    return wrapper#对于带参函数import functoolsdef log(text):    def decorator(func):        @functools.wraps(func)        def wrapper(*args, **kw):            print ‘%s %s():‘ % (text, func.__name__)            return func(*args, **kw)        return wrapper    return decorator``
Partial function (fixed function default value)
``>>> import functools>>> int2 = functools.partial(int, base=2)>>> int2(‘1000000‘)64>>> int2(‘1010101‘)85#相当于：def int2(x, base=2):    return int(x, base)max2 = functools.partial(max, 10)``

Equivalent to `max` specifying the first argument for a function

``max2(5, 6, 7)#相当于：max(10, 5, 6, 7)``

Python Learning notes-function Chapter

Related Keywords:

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.