python function

Because the arguments to power in the final invocation of it are named, their order is irrelevant; the arguments are associated with the parameters of the same name in the definition is called key-word passing

Keyword passing, in combination with the default argument capability of Python functions, can be highly useful when you're defining functions with large numbers of possible arguments, most of which have common defaults.

Python functions can also be defined to handle variable numbers of arguments.

Prefixing the final parameter name of the function with a * causes all excess nonkeyword arguments in a call of a function to be collected together and assigned as a tuple to the given parameter.

If the final parameter in the parameter list is prefixed with **, it will collect all excess keyword-passed arguments into a dictionary.

Arguments are passed in by object reference. The parameter becomes a new reference to the object. For immutable objects( such as tuples, strings,and numbers), what is done with a parameter has no effect outside the function.

global

nonlocal, causes an identifier to refer to a previously bound variable in the closest enclosing scope.

lambda expressions are anonymous little functions that you can quickly define inline.

lambda parameter1, parameter2, . . .: expression

A generator function is a special kind of function that you can use to define your own iterators. When you define a generator function, you return each iteration's value using yield keyword.

Depending on how it's used, a generator that doesn't have some condition to halt it could cause an endless loop when called.

A decorator is syntactic suger for this process and lets you wrap one function inside another with a one-line addition. (like js closure,java aop)

def decorate(func):
    print(" in decorate function, decorating", func.__name__)
    def wrapper_func(*args):
        print("executing", func.__name__)
        return func(*args)
    return wrapper_func


@decorate
def myfunc(parameter):
    print(parameter)

 

posted on 2012-08-13 10:59  grep  阅读(773)  评论(0编辑  收藏  举报