python | custom function


Section 1 custom function

1.1 Definition of functions

Function is a piece having a specific function, reusable group of statements. python in function with the function name is represented by a function call and the function name. It is a functional abstraction, similar to the black box, so if we can understand the function of the input and output can be, do not go into the internal implementation principle. The most prominent advantage is a function of:

  • Achieve code reuse : reduce repetitive work
  • Ensure consistent Code : only need to modify the function code, all calls can be affected

In python functions can be divided into: the system comes with a function, a third-party library functions, custom functions. It is important to know is "custom function」 .



Custom Functions

自定义函数语法:

def 函数名([参数列表]):
    函数体
    return语句

# 示例
def add1(x):
    x = x + 1
    return x

Function "return value" by "parameters" and to convey information, and achieve control of both by "parameter list" and "return statement", see the figure below:

Precautions:

  • Need to be declared parameter type (determined by the type of argument when calling) function definition; also need to specify the type of the return value (determined by the return statement)
  • Custom functions even without any parameters, a team must remain empty parentheses ()
  • Parentheses following the colon (:) essential
  • Function relative to the def keyword must be indented relationship
  • function allows nested definitions python
  • The return statement is the role of the end of the function call, and returns the result to the caller
    • The return statement is optional, it can appear anywhere in the body of the function
    • No return statement, there is no return statement is executed, there is no return statement and return value three cases, the functions return None


1.2 function calls

After you define a good function, there are two ways to call them:

  • From this document call : + direct function name passed parameters, such as add1 (9)
  • Called from other files : There are two ways to achieve this means
    • First specify the file path + import file name, and then the file name. Function name (parameter list) call
    • + From first specify a file path name of the file import function name, then the file name. Function name (parameter list) call
# 从本文件调用
def add1(x):
    x = x+2
    return x

add1(10)

# 从其他文件调用:从名为addx的文件调用已经定义好的add1函数
import os
os.chdir('D:\\data\\python_file') 

# 从其他文件调用方法1
import addx
addx.add1(4)

# 从其他文件调用方法2
from addx import add1
add1(9)



Program entry

Such as C, C ++ language, etc. have a main function of the entry as a program, to the main calling function library, the library can not call each other (between A and B shown below), i.e. run the program is to start from the main function . The python scripting language, there is no unified entrance, between the library can call each other.

So, python code execution There are two cases:

  • Case 1: directly as a script execution that directly run the modules
  • Case 2: The first import to other python module and then call execute ( module reuse ), in fact, "third-party libraries」 .

The python by if__name__ == 'main': statement, the control code is executed in two different cases.



if__name__ == 'main': simulation inlet

Python code execution mechanism based on the available if__name__ == 'main': inlet simulation program statement, to achieve control of the python code execution.

  • In direct execution script, if__name__ == 'main': end of the statement is executed (mostly a function of the statement correctness verification statement)
  • When the import is executed to the other modules, if__name__ == 'main': end of the statement is not executed
# 直接作为脚本执行
def add1(x):
    x = x+2
    return x
add1(10)

# 模块重用执行
import os
os.chdir('D:\\data\\python_file') 
from addx import add1
add1(9)

So, I want to run the script when only the direct command of execution, command these statements may be placed if__name__ == 'main': statement after the judgment:

# 自定义一个函数add1
def add1(a):
    a=a+1
    return a
print(__name__)

if __name__ == "__main__":       # 脚本直接执行时,运行后面的语句;被import执行时,不运行后面的语句
    print(add1(2))               # 函数正确性验证和测试


1.3 Function parameters

1.3.1 Types of actual parameter

From the above, the three most important part is the function argument, the function body, return values, and the parameters are divided into parameter arguments:

  • Parameter: the definition of the function name, variable in parentheses behind
  • Argument: when you call the function, the function name in parentheses behind variables

Precautions:

  1. Parameter function valid only within, a parameter may have no function, but it must be enclosed in parentheses ()
  2. Usually modify parameter does not affect the argument; but if passed to the function is "variable sequence" (lists, dictionaries, collections), modify the shape affect participants arguments
def printmax(a,b):       # a, b是形参
    if a>b:
        print(a)
 printmax(3,4)           # 3, 4是实参

# 形参修改不影响实参
def add2(x):
    x = x+2
    return x

x = 10
print(add2(x))  
print(x)

# 形参修改影响实参
def add2(x):              
    x.append(2)           
    return x

y = [1, 1]                # 实参y是变序列(列表、字典、集合)
print(add2(y))            # 函数返回值
print(y)                  # 修改形参影响实参


1.3.2 pass parameters

When defining the function need not specify the type of parameter, when calling the function, Python will automatically infer argument types. And the process of calling a function and the function is defined, can be simplified into the following three-step drawing, in essence, transfer information parameters and return values, and transmission parameters occurs in the first and third steps by.

Parameters varied functions, parameter passing sequence according to occur, some common parameters can be learned from two perspectives:

  • Defined functions (parameters): The default value of the parameter, the variable parameter
  • Call the function (arguments): positional parameters, keyword parameters, named keyword arguments

At the same time, these parameters may be used in combination (not variable parameters and parameter combinations of keywords), and the order of parameters defined from left to right are: position parameter >> >> default value of the parameter variable parameter / parameter keyword / key named word parameters. There is also a high-level usage parameter passing - a sequence of parameters passed to unpack.



The default value of the parameter

The default parameter is to use some of the parameters contain default values ​​when calling the function.

# 默认值参数b=5, c=10
def demo(a, b=5, c=10):
    print(a, b, c)

demo(1, 2)

Precautions:

  • The default value of the parameter must appear in the parameter list of the extreme right
  • When you call the function with default parameter values, you can assign default values ​​for the parameters, you can not assign
  • The default value of the parameter only immutable objects used as the default value of the variable sequence, there will be a program logic error
  • You can use "function name .defaults" View all default parameters of the function of the current value



variable parameter

The variable parameter is allowed to pass more than (≥0) argument when calling parameters, variable parameters are divided into two situations:

  • Variable position parameters : When defining parameters, preceded by a *, indicates that the parameter is variable, can accept any number of parameters that constitute a "tuple" can only pass parameters by position
  • Variable keyword arguments : the definition of parameters, preceded by ** denotes a variable parameter that can accept any number of parameters that constitute a "dictionary", only through keyword arguments passed
# 可变位置参数
def demo(*p):
    print(p)
    
demo(1, 2, 3)                 # 参数在传入时被自动组装成一个元组

# 可变关键字参数
def demo(**p):
    print(p)

demo(b='2', c='5', a='1')     # 参数在传入时被自动组装成一个字典



Positional parameters

Characteristic parameter is the position of the function is called, to ensure consistent sequence of arguments and parameters, the same number.

# 位置参数
def demo(a, b, c):
    print(a, b, c)

demo(1, 2, 3)



Keyword arguments

Keyword parameters allow incoming zero or more parameters as a dictionary at the time of call, and the linkages and values ​​when parameters are passed by an equal sign in (=). Keyword parameters biggest advantage is that the argument can not match the order and the order parameter, but does not affect the results transmitted.

# 关键参数
def demo(a, b, c):
    print(a, b, c)

demo(b=2, c=5, a=1)   # 改变参数顺序对结果不影响



Named keyword arguments

命名关键字参数是在关键字参数的基础上,限制传入的的关键字的变量名。和普通关键字参数不同,命名关键字参数需要一个用来区分的分隔符*,它后面的参数被认为是命名关键字参数。

# 这里星号分割符后面的city、job是命名关键字参数
def person_info(name, age, *, city, job):
    print(name, age, city, job)

person_info("Alex", 17, city="Beijing", job="Engineer")



参数传递的序列解包

参数传递的序列解包,是通过在实参序列前加星号(*)将其解包,然后按顺序传递给多个形参。根据解包序列的不同,可以分为如下5种情况:

序列解包 示例
列表的序列解包 *[3,4,5]
元组的序列解包 *(3,4,5)
集合的序列解包 *{3,4,5}
字典的键的序列解包 若字典为dic={'a':1,'b':2,'c':3},则解包代码为:*dic
字典的值的序列解包 若字典为dic={'a':1,'b':2,'c':3},则解包代码为:*dic.values()

注意事项:

  • 对实参序列进行序列解包后,得到的实参值就变成了位置参数,要和形参一一对应
  • 当序列解包和位置参数同时使用时,序列解包相当于位置参数,且会优先处理
  • 序列解包不能在关键字参数解包之后,否则报错
"""函数参数的序列解包"""
def demo(a, b, c):
    print(a+b+c)

demo(*[3, 4, 5])       # 列表的序列解包
demo(*(3, 4, 5))       # 元组的序列解包
demo(*{3, 4, 5})       # 集合的序列解包

dic = {'a': 1, 'b': 2, 'c': 3}
demo(*dic)             # 字典的键的序列解包              
demo(*dic.values())    # 字典的值的序列解包

"""位置参数和序列解包同时使用"""
def demo(a, b, c):  
    print(a, b, c)

demo(*(1, 2, 3))       # 元组的序列解包
demo(1, *(2, 3))       # 位置参数和序列解包同时使用
demo(c=1, *(2, 3))     # 序列解包相当于位置参数,优先处理,正确用法
demo(*(3,), **{'c': 1, 'b': 2})  # 序列解包必须在关键字参数解包之前,正确用法


1.4 全局变量与局部变量

变量起作用的代码范围称为「变量的作用域」。不同作用域内变量名可以相同,但互不影响。从变量作用的范围分类,可以把变量分类为:

  • 全局变量:指函数之外定义的变量,在程序执行全过程有效
  • 局部变量:指在函数内部使用的变量,仅在函数内部有效,当函数退出时变量将不存在

需要特别指出的是,局部变量的引用比全局变量速度快,应考虑优先使用。



全局变量声明

有两种方式可以声明全局变量:

  • 方式一:在函数外声明
  • 方式二:在函数内部用global声明,又分为两种情况:
    • 情况1:变量已在函数外定义,使用global声明。若进行了重新赋值,则赋值结果会覆盖原变量值
    • 情况2:变量未在函数外定义,使用global在函数内部声明,它将增加为新的全局变量

特殊情况,若局部变量和全局变量同名,那么全局变量会在局部变量的作用域内被隐藏掉。

d = 2       # 全局变量
def func(a, b):
    c = a*b
    return c

func(2, 3)

def func(a, b):
    c = a*b
    d = 2   # 局部变量
    return c

func(2, 3)

"""声明的全局变量,已在函数外定义"""
n = 1
def func(a, b):
    global n
    n = b
    c = a*b
    return c

s = func("knock~", 2)
print(s, n)

"""声明的全局变量,未在函数外定义,则新增"""
def func(a, b):
    c = a*b
    global d  # 声明d为全局变量
    d = 2
    return c

func(2, 3)

"""局部变量和全局变量同名,则全局变量在函数内会被隐藏"""
d = 10                   # 全局变量d
def func(a, b):
    d = 3                # 局部变量d
    c = a+b+d
    return c

func(1, 2)
d


1.5 lambda函数

lambda函数,又称匿名函数,即没有函数名字临时使用的小函数。其语法如下:

lambda 函数参数:函数表达式

注意:
    - 匿名函数只能有一个表达式
    - 该表达式的结果,就是函数的返回值
    - 不允许包含其他复杂语句,但表达式中可以调用其他函数

lambda函数的使用场景,主要在两方面:

  • 尤其适用于需要一个函数作为另一个函数参数的场合,比如排序
  • 把匿名函数赋值给一个变量,再利用变量来调用该函数
def f(x, y, z): 
    return x+y+z         # 位置参数
f(1, 2, 3)

def f1(x, y=10, z=10): 
    return x+y+z         # 默认值参数
f(1)

"""把匿名函数赋值给一个变量,再利用变量来调用该函数,作用等价于自定义函数"""
f=lambda x,y,z:x+y+z
f(y=1,x=2,z=3)           #关键值参数

L = ['ab', 'abcd', 'dfdfdg', 'a']
L.sort(key=lambda x: len(x))               # 按长度排序
L

L=[('小明',90,80),('小花',70,90),('小张',98,99)]
L.sort(key=lambda x:x[1],reverse=True)     # 降序排序
L


1.6 递归


在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。但不是的函数调用自己都是递归,递归有其自身的特性:

  • 必须有一个明确的递归结束条件,称为递归出口(基例
  • 相邻两次重复之间有紧密的联系,前一次要为后一次做准备(通常前一次的输出就作为后一次的输入)
  • 每一次递归,整体问题都要比原来减小,并且递归到一定层次时,要能直接给出结果



从上图可知,递归过程是函数调用自己,自己再调用自己,...,当某个条件得到满足(基例)的时候就不再调用,然后再一层一层地返回,直到该函数的第一次调用。递归函数的优点是逻辑简单清晰,缺点是过深的调用会导致栈溢出,在Python中,通常情况下,这个深度是1000层,超过将抛出异常。



案例:用递归实现阶乘

# 案例一:用递归实现阶乘
def fact(n):
    if n==0:
        return 1
    else:
        return n*fact(n-1)
fact(5)

# 案例二:实现字符串反转
# 方法1,先转成列表,调用列表的revers方法,再把列表转成字符串
s = 'abcde'
l = list(s)
l.reverse()
''.join(l)

# 方法2,切片的方法
s = 'abcde'
s[::-1]

# 方法3,递归的方法
s = 'abc'
def reverse1(s):
    if s == '':
        return s
    else:
        print(s)
        return reverse1(s[1:])+s[0]

reverse1(s)

Guess you like

Origin www.cnblogs.com/1k-yang/p/12324248.html