Python functional programming

Source: Internet
Author: User

1 callable built-in functions determine whether a name is a callable Function

>>> import math>>> x = 1>>> y = math.sqrt>>> callable(x)False>>> callable(y)True

2 record function (document string)

>>> def square(x):    'calculates the square of number x'    return x * x>>> square.func_doc'calculates the square of number x'

 

3. Can I change the form parameter and actual parameter? The character string, number, and tuples are different from the sequence parameters.
Parameters are stored in local scopes.

4. Keyword parameters and default values

>>> Def say_hello (greeting = 'hello', name = 'jmz', biaodian = '!!! '): Print' % s, % S % s' % (greeting, name, biaodian) # in this way, you can call both >>> say_hello () Hello, JMZ! >>> Say_hello (name = 'yyer', biaodian = '~~~ ') Hello, yyer ~~>> Say (name = 'yyer', greeting = 'Hi, Hi') >>> say_hello (name = 'yyer', greeting = 'Hi, Hi') Hi, hi, yyer !!!

 

5. Collect Parameters

1) collect parameters as tuples

Example 1:

>>> def print_params(*params):    print params    >>> print_params('param1')('param1',)>>> print_params('param1','param2','param3')('param1', 'param2', 'param3')>>>>>> 

 

Example 2:

>>> def print_params_2(title,*params):    print title    print params>>> print_params_2('title',1,2,3,4,5)title(1, 2, 3, 4, 5)

 

2) collect parameters as dictionaries:

>>> def print_params_4(x,y,z = 3,*pp,**ppp):    print x,y,z    print pp    print ppp    >>> print_params_4(1,2,4,'pp1','pp2','pp3',ppp1 = 'aaa',ppp2 = 'bbb')1 2 4('pp1', 'pp2', 'pp3'){'ppp1': 'aaa', 'ppp2': 'bbb'}>>> 

 

3) function calls using collection Parameters

>>> def hello(**params):    print params['greeting'],params['name']    >>> params = {'greeting':'Hello','name':'JMZ'}>>> hello(**params)Hello JMZ>>>

 

6. Scope

1) What is a variable? You can think of it as the value name, just like a dictionary. The key reference value is executed in a = (1, 2, 3) reference the name to the tuples. In fact, this is very close to the real situation. The variables and their corresponding values are invisible dictionaries.

The built-in vars () function returns this dictionary:

IDLE 2.6.5      ==== No Subprocess ====
>>> vars()
{'__builtins__': <module '__builtin__' (built-in)>, '__file__': '/usr/bin/idle-python2.6', '__package__': None, '__name__': '__main__', 'main': <function main at 0xb6cc1f44>, '__doc__': None}
>>> def printhello():
print 'hello world'


>>> x = 1
>>> a = (1,2,3)
>>> vars()
{'a': (1, 2, 3), 'printhello': <function printhello at 0x9fea6bc>, '__builtins__': <module '__builtin__' (built-in)>, '__file__': '/usr/bin/idle-python2.6', '__package__': None, 'x': 1, '__name__': '__main__', 'main': <function main at 0xb6cc1f44>, '__doc__': None}

>>> vars()['a']
(1, 2, 3)
>>>

2) local variables and global variables

You can directly reference global variables in the function, but be cautious. using too many variables is prone to errors.
Name blocking:
If the name of the local variable inside the function is the same as that of the external global variable, the local variable is referenced. You can use the globals () function to obtain the global variable dictionary () returns the dictionary of all variables. Globals () ['var1'] returns the value of global variable var1.

3) nested Scope

In python, you can define functions within a function:

>>> def outFunction(outVar):
a = 2
def inFunction(inVar):
return outVar * inVar * a
return inFunction

>>> inFunc = outFunction(5)
>>> inFunc(4)
40
>>>

 

Where is it useful: When an out function is required to create an in function.

Rule: the return value of the out function is a function that returns the in function itself. It is important that the returned function can also access the scope of its definition, that is, the returned inner function carries its environment + its own local variables.

7 functional programming-some useful functions

1) Use the map function to pass all the elements in the sequence to a function:
Map (function, sequence)

2) The filter function can be used to filter elements by a function that returns boolean values:

>>> def func(x):
return x.isalnum()

>>> seq = ['foo','x41','!***']
>>> filter(func,seq)
['foo', 'x41']
>>>

Of course, you can also use the list derivation formula:
>>> [X for X in seq if X. isalnum ()]
['Foo', 'x41']

3) Lambda expression features create short functions:

>>> Filter (lambda X: X. isalnum (), SEQ)
['Foo', 'x41']

4) Reduce Function

Reduce (func, SEQ) combines the first two elements of a sequence with a given function, and continues to combine and use their return values with the third element, knowing that the entire sequence has been processed:

>>> Seq = [1, 2, 4, 6, 7, 12, 23]
>>> Reduce (lambda X, Y: X + Y, SEQ)
55
>>>

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.