V. function

1. Function Definition

The function blocks of code that is packaged into a particular container, the container only needs to use the specific function, which will run through the internal code of the function call.

def fun(参数):
    函数块
    return 返回值

1.1 Katachisan

Defined parameters of the function.

  • Positional parameters
def fun(name, age, num):
    pass
  • Keyword arguments
def fun(name = 'aaron', age = 20, num = '201620'):
    pass
  • note

    • When the positional parameters and keyword parameters mix, location parameters must be before the keyword arguments.
    def fun(name, age, num = '201620'):
        pass
    • For the default value of the function used with caution variable types.
    # 如果想要给value设置默认值是空列表
    
    # 不推荐
    # 因为在建立函数时, 就已经创建了一个空列表. 在调用函数时, 若不传递value参数, 则调用的函数执行时, value指向同一个地址。
    def func(data, value = []):
        pass
    
    # 推荐
    def func(data, value = None):
        if not None:
            value = []
    • example

      # 方法一
      def func(data, value = []):
          value.append(data)
          return value
      
      v = func(1)
      v1 = func(1,[11,22,33])
      print(v)
      v2 = func(2)
      print(v,v1,v2)
      
      # 输出结果
      [1]
      [1, 2] [11, 22, 33, 1] [1, 2]
      # 方法二
      def func(data, value = None):
          if not value:
              value = []
          value.append(data)
          return value
      
      v = func(1)
      v1 = func(1,[11,22,33])
      print(v)
      v2 = func(2)
      print(v,v1,v2)
      
      #输出结果
      [1]
      [1] [11, 22, 33, 1] [2]
  • Special parameter

    def func(*args, **kwargs):
        pass
    
    # 其中*args用来接受除字典以外的其他类型的参数, **kwargs用来接受字典类型的参数

1.2 argument

When you call the function, passing the parameters.

def fun(name, age, num):
    pass
fun('aaron', 20, '201620')
  • note

    Parameter transfer function memory address (reference).

1.3 Return Values

Who calls a function, the return value of a function assigned to it who, when not specify a return value, default return None.

def fun(name, age, num):
    return name, age, num
  • note
    • Function is not called, the internal function statement will not be executed !!!
    • Each time a function call, the call will be to open up a memory, the memory can hold the value of their future want to use.

2. anonymous function

  • definition

    The so-called anonymous function is not the function of the function name, but with the lambda keyword to define.

lambda x, y: x + y
  • The above formulas are functionally equivalent to the following function.
def fun(x, y):
    return x + y

3. recursive function

  • Function calls itself
def recursion():
    num = input('请输入一个阿拉伯数字:')
    if num.isdecimal():
        print('输入成功')
    else:
        print('\n输入错误! 重新开始!\n')
        recursion() # 在此处调用了自己

recursion()

4. Closure

  • definition

    Create an area for the function (internal variables for their own use), providing data for it later execution.

name = 'oldboy'
def bar(name):
    def inner():
        print(name)
    return inner
v1 = bar('alex') # {name = alex, inner} # 闭包
v2 = bar('eric')
v1()
v2()
  • example

    • Example 1
    name = 'alex'
    def base():
        print(name)
    
    def func():
        name = 'eric'
        base()   
    func()
    
    # 输出结果为
    alex
    • Example 2
    info = []
    
    def func(i):
        def inner():
            print(i)
        return inner
    
    for item in range(10):
        info.append(func(item))
    
    info[0]()
    info[1]()
    info[4]()
    
    # 输出结果为
    0
    1
    4
    • Example 3
    name ='aaron'
    def fun():
        def inner():
            print(name)
        return inner() # 相当于 v = inner();return v  inner无返回值,所以v = None, 调用fun()的返回值就为None
        # return inner # 若语句为左边所示,则最后的输出结果为inner函数所在的内存地址
    r = fun()
    print(r)
  • note

    # 不是闭包
    def bar(name):
        def inner():
            return 123
        return inner
    
    # 是闭包: 封装值 + 内层函数需要使用
    def bar(name):
        def inner():
            print(name)
            return 123
        return inner

5. Built-in functions

  • Common built-in functions
id:# 查看地址值
type:# 查看类型
dir:# 获取当前数据内置的方法属性
len:# 求长度
range:# 生成一系列的数字
open:# 打开文件
input:# 输入
print:# 输出
help:# 帮助

'''
注意:关于上述提到的id是用来查看地址值的,这里补充一下is和==的区别。
is:用来判断两个变量的地址是否相同。
==:用来判断两个变量的值是否相同。
'''
  • Advanced built-in functions

    • map, an iterative loop for each element may be an object, and then perform the function of each element, each of the saved execution results to an iterator and returns.
    # 格式:map(函数, 可迭代对象)
    
    v1 = [1, 2, 3, 4, 5]
    # 将v1中的每个元素都加10
    result1 = map(lambda x: x + 10, v1)
    # 将v1中的每个元素都乘10
    result2 = map(lambda x: x * 10, v1)
    
    print(result1)
    result3 = []
    for i in result1:
        result3.append(i)
    print(result3)
    
    print(result2)
    result4 = []
    for i in result2:
        result4.append(i)
    print(result4)
    
    # 输出结果
    <map object at 0x0000021384B5E940>
    [11, 12, 13, 14, 15]
    <map object at 0x0000021384B89FD0>
    [10, 20, 30, 40, 50]
    • filter, may be an iterative loop for each element of the object, and then perform the function of each element, each element satisfies the stored condition to a function iterator and returns.
    # 格式:filter(函数, 可迭代对象)
    
    v1 = [11, 22, 'aa', 33, 'bb']
    # 求v1中类型为int的元素
    result1 = filter(lambda x: type(x) == int, v1)
    # 求v1中类型为str的元素
    result2 = filter(lambda x: type(x) == str, v1)
    
    print(result1)
    result3 = []
    for i in result1:
        result3.append(i)
    print(result3)
    
    print(result2)
    result4 = []
    for i in result2:
        result4.append(i)
    print(result4)
    
    # 输出结果
    <filter object at 0x00000175EADDD048>
    [11, 22, 33]
    <filter object at 0x00000175EBE5CBA8>
    ['aa', 'bb']
    • note

      map and filter the return value is an iterator , if the direct output, the resulting value is an address; cycle operation to be obtained for its value; or use list () will be cast directly into a list iterators, direct get its value.

      v1 = [11, 22, 'aa', 33, 'bb']
      result = filter(lambda x: type(x) == int, v1)
      print(list(result))
      
      # 输出结果
      [11, 22, 33]

      Above said execution result in the release of Python3; if at the release Python2, map and filter the return value is a list.

    • reduce, the elements may be executed loop iteration object function, the function must have two parameters, each two parameters are passed in a previous execution result obtained (only the first parameter is passed the second the two parameters), the end result will be saved to an iterator and returns. This is a function block functools in the place where it is because of its use and the map, filter similar.

    # 格式:reduce(函数, 可迭代对象)
    
    from functools import reduce
    v1 = [1, 10, 100, 1000]
    # 求v1中元素的和
    result1 = reduce(lambda x, y: x + y, v1)
    # 求v1中元素的乘积
    result2 = reduce(lambda x, y: x * y, v1)
    print(result1)
    print(result2)
    
    # 输出结果
    1111
    1000000

Guess you like

Origin www.cnblogs.com/aaron-zhou/p/11784804.html