Python-Functional programming

Source: Internet
Author: User

15. Functional Programming

Create a function

def function_name (arguments): "" "    function Documention_string" ""    function_body_suite

1. Declaration and definition:

2. Forward reference

Like other high-level languages, Python does not allow references or calls to a function before it is declared.

3. Properties of functions

For example, create two py files, test1.py;test2.py, as follows:

test1.py--------------------------ST = ' test1 ' def Bar ():    ' This is bar '    print ' OK '
#函数必定有返回值, default is None
test2.py
--------------------------------------Import Test1print test1. Stprint Test1.bar () #-----------output #test1#ok#none#-----------Remember that the process is the function of the return value None def foo (): ' ' This is    foo '    print ' foo ' print foo.__doc__   #This is foo

4. Nested functions

>>> def foo ():
        def bar ():            print ' Bar () is called '        print ' foo () are called '        Bar ()   >>> foo () foo () is Calledbar () I S called>>> Bar ()
Traceback (most recent):  File "<pyshell#5>", line 1, in <module>    bar () Nameerror:name ' bar ' is not defined

Because bar () is within the scope of Foo (), the bar cannot be referenced outside.

5. Transfer function

1. Other variables can be aliases of functions, because the object reference

All objects are passed by reference, and functions are no exception, and when you assign a value to a variable, the reference to the same object is actually assigned to that variable. If the object is a function, all aliases for that object are callable.

def foo ():
    print ' foo ' bar = foo   #函数对象的引用bar ()   #函数对象的调用 # output Foo

Note: foo: reference to function object; foo (): Call to function object

2. Functions are passed into other functions as parameters to invoke

Always remember: the difference between a function object, a reference and a call is a few key words.

def foo ():
    print ' foo ' def Bar (argfunc):    print ' in Bar () '    argfunc ()    bar (foo)    #把函数作为参数传入其他函数来调用 # output: #in bar () #foo
Local variable argfunc is equivalent to the alias of the function object foo

In the following:

#内建函数int ()/float ()/long () conversion, implementation function transfer and invocation
def convert (argfunc,seq):    return [Argfunc (obj) for obj in seq]lis = [123,15.23,-6.2e5,99999999l]print convert (int, LIS) #[123, -620000, 99999999]print convert (float,lis) #[123.0, 15.23, -620000.0, 99999999.0]print convert (long, LIS) #[123l, 15L, -620000l, 99999999L]
6, formal Arguments

1. Position parameters

are passed in the exact order defined by the function, and if there are no default parameters, the number of incoming parameters is consistent.

Common errors are as follows:

Takes no arguments (1 given)

Takes exactly 2 arguments (1 given) et cetera

2. Default parameters

def foo (arg,default1 = ' Python ', default2 = ' Django '):    Pass

Each default parameter is followed by an assignment statement with a default value, and if no value is given when the function is called, the default value is used.

The default parameter is best written in the last

3. Keyword parameters

def foo (arg,obj1= ' good ', obj2=10):    return arg,obj1,obj2print foo (arg= ' begin ')   # (' Begin ', ' good ', ten) print Foo (' Begin ')       # (' Begin ', ' good ', ten) print foo (' Begin ', ' Python ')  # (' Begin ', ' python ', ') #print foo (arg= ' begin ')    # Error print foo (arg= ' begin ', obj2=100)  # (' Begin ', ' good ', ') print foo (obj2=100,arg= ' begin ', obj1= ' Ok ')    # (' Begin ', ' Ok ', 100)

7. Variable length parameters

1. Variable length parameter and non-variable length parameter

"" "using an asterisk before the parameter name means that the function accepts any number of positional arguments" "Def Multiply (*args): Total    = 1 for    arg in args:        total+=arg    return totalprint multiply ()        #1print multiply (     #4print multiply (4,5,6)   #16
"" "Python uses 2 asterisks before the parameter name to support any number of keyword arguments" "
def multiply2 (**kwargs): For    Key,value in Kwargs.items ():        print '%s=>%s '% (key,value)        multiply2 () Multiply2 (name= ' begin ')                  #name =>beginmultiply2 (name= ' begin ', age= ' ", tel=110)
#顺序defcomplex_function(a,b=None,*args,**kwarg):    pass#测试defadd(a,b,c):    returna+b+cprintadd(a=10,b=10,c=10)args=(2,3)printadd(1,*args)  #6kwargs={‘b‘:100,‘c‘:200}printadd(100,**kwargs) #400printadd(a=100,**kwargs)   #400#print add(a=100,*args)      #TypeError: add() got multiple values for keyword argument ‘a‘printadd(1,2,c=3)  #6printadd(1,2,b=3)  # add() got multiple values for keyword argument ‘b‘

Three -dimensional expressionTrue if the result of the if decision condition else is false
If 5>3 else 0

is to output the result first, then determine the condition
Output 1, if 5 is greater than 3, otherwise output 0

Python-Functional programming

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.