python - functions

函数是一块可重用的代码,用于执行单个相关操作。 函数为您的应用程序提供更好的模块性,并提供高度的代码重用。
正如你已经知道的那样,Python为你提供了许多内置的函数,如print()等,但是你也可以创建你自己的函数。 这些功能被称为用户定义的功能。

定义一个函数

1、函数以关键字def开头,后跟函数名和括号(())。
2、任何输入参数或参数都应放在这些括号内。 您也可以在这些括号内定义参数。
3、函数的第一个语句可以是一个可选语句 – 函数的功能说明。
4、每个函数中的代码块都以冒号(:)开始,并且是缩进的。
5、语句return [表达式]退出函数,可选地将表达式传回给调用者。 没有参数的返回语句与返回无相同。

语法

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

默认情况下,参数具有位置行为,您需要按照它们定义的顺序通知它们。

例子

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

调用函数

定义函数只给它一个名称,指定要包含在函数中的参数并构造代码块。
一旦函数的基本结构完成后,您可以通过从另一个函数或直接从Python提示符调用它并执行它。

例子

代码

# Function definition is here
def printme( str ):
   "This prints a passed string into this function"
   print str
   return;

# Now you can call printme function
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

Pass by reference vs value

Python语言中的所有参数(参数)均通过引用传递。 这意味着,如果您更改某个函数中参数的含义,则该更改也会反映到调用函数中。

例子

代码

# Function definition is here
def changeme( mylist ):
   "This changes a passed list into this function"
   mylist.append([1,2,3,4]);
   print "Values inside the function: ", mylist
   return

# Now you can call changeme function
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]]

还有一个例子,其中参数被引用传递,引用被覆盖在被调用的函数内部。

代码

# Function definition is here
def changeme( mylist ):
   "This changes a passed list into this function"
   mylist = [1,2,3,4]; # This would assig new reference in mylist
   print "Values inside the function: ", mylist
   return

# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

结果

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

说明:参数mylist对于函数changeme是本地的。 在函数内改变mylist不会影响mylist。

函数参数

Required arguments

必需的参数要以正确的位置顺序传递给函数的参数。 函数调用中参数的数量应该与函数的定义完全匹配。
要调用函数printme(),您肯定需要传递一个参数,否则会给出语法错误。

例子

代码

# Function definition is here
def printme( str ):
   "This prints a passed string into this function"
   print str
   return;

# Now you can call printme function
printme()

结果

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

Keyword arguments

关键字参数与函数调用相关。 当在函数调用中使用关键字参数时,调用参数名称标识参数。
这允许您跳过参数或将其置乱,因为Python解释器能够使用提供的关键字来将值与参数匹配。

例子

代码

# Function definition is here
def printme( str ):
   "This prints a passed string into this function"
   print str
   return;

# Now you can call printme function
printme( str = "My string")

结果

My string

下面的例子给出了更清晰的图片。 请注意参数的顺序无关紧要。

代码

# Function definition is here
def printinfo( name, age ):
   "This prints a passed info into this function"
   print "Name: ", name
   print "Age ", age
   return;

# Now you can call printinfo function
printinfo( age=50, name="miki" )

结果

Name:  miki
Age  50

Default arguments

默认参数是一个参数,如果该参数的函数调用中未提供某个值,则该参数将采用默认值。

例子

代码

# Function definition is here
def printinfo( name, age = 35 ):
   "This prints a passed info into this function"
   print "Name: ", name
   print "Age ", age
   return;

# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )

结果

Name:  miki
Age  50
Name:  miki
Age  35

Variable-length arguments

您可能需要处理函数以获取比定义函数时指定的更多参数。 这些参数被称为可变长度参数,并且不需要在函数定义中命名,与所需参数和默认参数不同。

语法

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

星号(*)放在保存所有非关键字变量参数值的变量名之前。 如果在函数调用期间未指定其他参数,则此元组保持空白。

例子

代码

# Function definition is here
def printinfo( arg1, *vartuple ):
   "This prints a variable passed arguments"
   print "Output is: "
   print arg1
   for var in vartuple:
      print var
   return;

# Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )

结果

Output is: 
10
Output is: 
70
60
50

The Anonymous Functions(匿名函数)

这些函数被称为匿名函数,因为它们没有使用def关键字以标准方式声明。 您可以使用lambda关键字创建小型匿名函数
1、Lambda可以接受任意数量的参数,但只能以表达式的形式返回一个值。 它们不能包含命令或多个表达式。
2、一个匿名函数不能直接调用来打印,因为lambda需要一个表达式
3、Lambda函数具有其自己的本地名称空间,并且不能访问其参数列表中的变量以及全局名称空间中的变量。
4、虽然看起来lambda是一个函数的单行版本,但它们不等同于C或C ++中的内联语句,出于性能原因,其目的是在调用期间通过传递函数堆栈分配。

语法

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

例子

代码

# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;

# Now you can call sum as a function
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )

结果

Value of total :  30
Value of total :  40

The return Statement

语句return [expression]退出函数,可选地将表达式传回给调用者。 没有参数的返回语句与返回空相同。

例子

代码

# Function definition is here
def sum( arg1, arg2 ):
   # Add both the parameters and return them."
   total = arg1 + arg2
   print "Inside the function : ", total
   return total;

# Now you can call sum function
total = sum( 10, 20 );
print "Outside the function : ", total 

结果

Inside the function :  30
Outside the function :  30

Scope of Variables(变量范围)

程序中的所有变量可能无法在该程序中的所有位置访问。 这取决于你声明变量的地方。
变量的范围决定了程序中可以访问特定标识符的部分。
1、Global variables
2、Local variables

Global vs. Local variables

在函数体内定义的变量具有局部范围,而在外部定义的变量具有全局范围。
这意味着局部变量只能在声明它的函数内部访问,而全局变量可以通过所有函数在整个程序体中访问。 当你调用一个函数时,在它内部声明的变量被引入到作用域中。

例子

代码

total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
   # Add both the parameters and return them."
   total = arg1 + arg2; # Here total is local variable.
   print "Inside the function local total : ", total
   return total;

# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total 

结果

Inside the function local total :  30
Outside the function global total :  0
    原文作者:庵下桃花仙
    原文地址: https://www.jianshu.com/p/6f82d2dda2b8
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞