亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

Python 函数详解:构建可复用代码模块的最佳实践

函数概述

函数是组织好、可复用的代码块,用于执行单一相关动能。函数提供更好的模块化和高度代码复用。

Python 提供许多内置函数如 print(),也可创建自己的函数,称为用户定义函数。

定义函数

定义函数提供所需功能。Python 定义函数的简单规则:

语法

def functionname(parameters):
    "function_docstring"
    function_suite
    return [expression]

默认参数为位置行为,需按定义顺序传递。

示例

以下函数接受字符串参数并打印到标准输出:

def printme(str):
    "This prints a passed string into this function"
    print str
    return

调用函数

定义函数仅给其命名、指定参数、构建代码块结构。基本结构确定后,可从另一函数或直接从 Python 提示符调用执行。调用 printme() 示例:

在线演示
#!/usr/bin/python
# 函数定义
def printme(str):
    "This prints a passed string into this function"
    print str
    return
# 调用 printme 函数
printme("I'm first call to user defined function!")
printme("Again second call to the same function")

执行结果:

I'm first call to user defined function!
Again second call to the same function

传引用 vs 传值

Python 所有参数(自变量)均传引用。即函数内改变参数引用的对象,变化反映回调用函数。例如:

在线演示
#!/usr/bin/python
# 函数定义
def changeme(mylist):
    "This changes a passed list into this function"
    mylist.append([1,2,3,4])
    print "Values inside the function: ", mylist
    return
# 调用 changeme 函数
mylist = [10,20,30]
changeme(mylist)
print "Values outside the function: ", mylist

这里维护传入对象引用并在同一对象追加值。输出结果:

Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

另一示例:参数传引用但在被调函数内重写引用:

在线演示
#!/usr/bin/python
# 函数定义
def changeme(mylist):
    "This changes a passed list into this function"
    mylist = [1,2,3,4]  # 给 mylist 赋新引用
    print "Values inside the function: ", mylist
    return
# 调用 changeme 函数
mylist = [10,20,30]
changeme(mylist)
print "Values outside the function: ", mylist

参数 mylist 局限于 changeme 函数。函数内改变 mylist 不影响外部 mylist。函数无实际作用,输出:

Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]

函数参数

可使用以下形式参数调用函数:

必需参数

必需参数按正确位置顺序传递给函数。函数调用参数数量必须与定义完全匹配。

调用 printme() 必须传一个参数,否则语法错误:

在线演示
#!/usr/bin/python
def printme(str):
    "This prints a passed string into this function"
    print str
    return
printme()

执行结果:

Traceback (most recent call last):
File "test.py", line 11, in 
printme()
TypeError: printme() takes exactly 1 argument (0 given)

关键字参数

关键字参数与函数调用相关。使用关键字参数时,调用者通过参数名标识参数。

这允许跳过参数或乱序放置,因 Python 解释器能用关键字匹配值与参数。可这样调用 printme():

在线演示
#!/usr/bin/python
def printme(str):
    "This prints a passed string into this function"
    print str
    return
printme(str="My string")

执行结果:

My string

更清晰示例,参数顺序无关:

在线演示
#!/usr/bin/python
def printinfo(name, age):
    "This prints a passed info into this function"
    print "Name: ", name
    print "Age ", age
    return
printinfo(age=50, name="miki")

执行结果:

Name: miki
Age 50

默认参数

默认参数在调用时未提供值则假定默认值。示例打印默认年龄(未传时):

在线演示
#!/usr/bin/python
def printinfo(name, age=35):
    "This prints a passed info into this function"
    print "Name: ", name
    print "Age ", age
    return
printinfo(age=50, name="miki")
printinfo(name="miki")

执行结果:

Name: miki
Age 50
Name: miki
Age 35

可变长参数

可能需处理比定义时更多的参数。这些称为可变长参数,定义时不命名,区别于必需/默认参数。

非关键字可变参数函数语法:

def functionname([formal_args,] *var_args_tuple):
    "function_docstring"
    function_suite
    return [expression]

星号 (*) 放在保存所有非关键字可变参数值的变量名前。调用时未指定额外参数则元组为空。简单示例:

在线演示
#!/usr/bin/python
def printinfo(arg1, *vartuple):
    "This prints a variable passed arguments"
    print "Output is: "
    print arg1
    for var in vartuple:
        print var
    return
printinfo(10)
printinfo(70, 60, 50)

执行结果:

Output is: 10
Output is: 70 60 50

匿名函数

匿名函数因不使用 def 关键字标准声明而得名。可用 lambda 关键字创建小匿名函数。

语法

lambda 函数语法仅含单语句:

lambda [arg1 [,arg2,.....argn]]: expression

示例展示 lambda 形式函数工作方式:

在线演示
#!/usr/bin/python
sum = lambda arg1, arg2: arg1 + arg2
print "Value of total : ", sum(10, 20)
print "Value of total : ", sum(20, 20)

执行结果:

Value of total : 30
Value of total : 40

return 语句

语句 return [表达式] 退出函数,可选将表达式返回调用者。无参数 return 等同于 return None。

前面示例均未返回值。可这样返回值:

在线演示
#!/usr/bin/python
def sum(arg1, arg2):
    total = arg1 + arg2
    print "Inside the function : ", total
    return total
total = sum(10, 20)
print "Outside the function : ", total

执行结果:

Inside the function : 30
Outside the function : 30

变量作用域

程序中所有变量并非在所有位置均可访问。这取决于变量声明位置。

变量作用域决定程序中可访问特定标识符的部分。Python 有两种基本变量作用域:

全局变量 vs 局部变量

函数体内定义的变量为局部作用域,外部定义为全局作用域。

即局部变量只能在声明它们的函数内访问,全局变量可被程序体所有函数访问。调用函数时,函数内声明的变量进入作用域。简单示例:

在线演示
#!/usr/bin/python
total = 0  # 全局变量
def sum(arg1, arg2):
    total = arg1 + arg2  # 此处 total 为局部变量
    print "Inside the function local total : ", total
    return total
sum(10, 20)
print "Outside the function global total : ", total

执行结果:

Inside the function local total : 30
Outside the function global total : 0

Python

  1. Stratasys FDM打印优化必知:Insight软件10大核心功能
  2. C++ 函数详解:从声明到调用的实战指南
  3. Python Lambda匿名函数实战指南
  4. Python 生成器:高效迭代与进阶用例
  5. Python 闭包详解:嵌套函数如何捕获变量
  6. 精通 Python 装饰器:专家技巧增强函数
  7. Python strip() 方法完全指南:去除首尾空白与自定义字符实战
  8. 精通 Python Lambda 函数:实用示例与最佳实践
  9. Python abs() 函数:计算数字与复数的绝对值
  10. Python round() 函数详解与实战示例
  11. 精通 Python map() 函数:语法、示例与最佳实践
  12. 精通 Python yield:生成器 vs return 实战指南