Python 简明教程

Python - Functions

Python 函数是一个有组织、可重用的代码块,用于执行单个的、相关的操作。函数为您的应用程序提供了更好的模块化和高度的代码重用。

A Python function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

自上而下的构建处理逻辑方法涉及定义独立的可重用的函数块。Python 函数可以通过传递所需数据(称为 parametersarguments )从任何其他函数调用。被调用的函数会将结果返回给调用环境。

A top-to-down approach towards building the processing logic involves defining blocks of independent reusable functions. A Python function may be invoked from any other function by passing required data (called parameters or arguments). The called function returns its result back to the calling environment.

python functions

Types of Python Functions

Python 提供以下类型的函数 -

Python provides the following types of functions −

Defining a Python Function

您可以定义自定义函数来提供所需的功能。以下是 Python 中定义函数的简单规则−

You can define custom functions to provide the required functionality. Here are simple rules to define a function in Python −

  1. Function blocks begin with the keyword def followed by the function name and parentheses ().

  2. Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.

  3. The first statement of a function can be an optional statement; the documentation string of the function or docstring.

  4. The code block within every function starts with a colon (:) and is indented.

  5. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

Syntax to Define a Python Function

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

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

By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.

一旦定义了该函数,您就可以通过从另一个函数或直接从 Python 提示符中调用它来执行它。

Once the function is defined, you can execute it by calling it from another function or directly from the Python prompt.

Example to Define a Python Function

以下示例展示如何定义函数 greetings()。括号是空的,所以没有任何参数。此处,第一行是文档字符串,函数块以 return 语句结束。

The following example shows how to define a function greetings(). The bracket is empty so there aren’t any parameters. Here, the first line is a docstring and the function block ends with return statement.

def greetings():
   "This is docstring of greetings function"
   print ("Hello World")
   return

调用此函数时,将打印 Hello world 消息。

When this function is called, Hello world message will be printed.

Calling a Python Function

定义函数仅给它一个名称,指定要包含在函数中的参数,并构造代码块。一旦函数的基本结构最终确定,您可以使用函数名本身来调用它。如果函数需要任何参数,则应将其放在括号内传递。如果函数不需要任何参数,则应保留括号为空。

Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code. Once the basic structure of a function is finalized, you can call it by using the function name itself. If the function requires any parameters, they should be passed within parentheses. If the function doesn’t require any parameters, the parentheses should be left empty.

Example to Call a Python Function

以下是调用 printme() 函数的示例−

Following is the example to call printme() function −

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

# Now you can call the function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")

当执行以上代码时,它会生成以下输出 −

When the above code is executed, it produces the following output −

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

Pass by Reference vs Value

在 C 和 C++ 等编程语言中,有两种向函数传递变量的主要方式,即按值调用和按引用调用(也称为按引用传递和按值传递)。然而,我们在 Python 中向函数传递变量的方式不同于其他方式。

In programming languages like C and C++, there are two main ways to pass variables to a function, which are Call by Value and Call by Reference (also known as pass by reference and pass by value). However, the way we pass variables to functions in Python differs from others.

  1. call by value − When a variable is passed to a function while calling, the value of actual arguments is copied to the variables representing the formal arguments. Thus, any changes in formal arguments does not get reflected in the actual argument. This way of passing variable is known as call by value.

  2. call by reference − In this way of passing variable, a reference to the object in memory is passed. Both the formal arguments and the actual arguments (variables in the calling code) refer to the same object. Hence, any changes in formal arguments does get reflected in the actual argument.

pass by reference vs value

Python 使用按引用传递机制。由于 Python 中的变量是对内存中对象的标签或引用,因此用作实际参数的变量和形式参数都真正地引用内存中的同一个对象。我们可以通过在传递之前和之后检查被传递变量的 id() 来验证此事实。

Python uses pass by reference mechanism. As variable in Python is a label or reference to the object in the memory, both the variables used as actual argument as well as formal arguments really refer to the same object in the memory. We can verify this fact by checking the id() of the passed variable before and after passing.

Example

在以下示例中,我们检查变量的 id()。

In the following example, we are checking the id() of a variable.

def testfunction(arg):
   print ("ID inside the function:", id(arg))

var = "Hello"
print ("ID before passing:", id(var))
testfunction(var)

如果执行以上代码,将会显示传递之前的 id() 和函数内部的 id()。

If the above code is executed, the id() before passing and inside the function will be displayed.

ID before passing: 1996838294128
ID inside the function: 1996838294128

行为还取决于传递的对象是可变的还是不可变的。Python 数值对象是不可变的。传递数值对象时,如果该函数更改了形式参数的值,它实际上会创建一个新的内存对象,使原始变量保持不变。

The behavior also depends on whether the passed object is mutable or immutable. Python numeric object is immutable. When a numeric object is passed, and then the function changes the value of the formal argument, it actually creates a new object in the memory, leaving the original variable unchanged.

Example

以下示例展示了将不可变对象传递给函数时的行为。

The following example shows how an immutable object behaves when it is passed to a function.

def testfunction(arg):
   print ("ID inside the function:", id(arg))
   arg = arg + 1
   print ("new object after increment", arg, id(arg))

var=10
print ("ID before passing:", id(var))
testfunction(var)
print ("value after function call", var)

它将生成以下 output

It will produce the following output

ID before passing: 140719550297160
ID inside the function: 140719550297160
new object after increment 11 140719550297192
value after function call 10

现在让我们将可变对象(例如列表或字典)传递给函数。它也按引用传递,因为传递前后的列表的 id() 相同。但是,如果我们在函数内部修改列表,其全局表示也将反映该更改。

Let us now pass a mutable object (such as a list or dictionary) to a function. It is also passed by reference, as the id() of list before and after passing is same. However, if we modify the list inside the function, its global representation also reflects the change.

Example

在这里,我们传递一个列表,附加一个新项目,然后查看原始列表对象的内容,我们会发现它已更改。

Here we pass a list, append a new item, and see the contents of original list object, which we will find has changed.

def testfunction(arg):
   print ("Inside function:",arg)
   print ("ID inside the function:", id(arg))
   arg=arg.append(100)

var=[10, 20, 30, 40]
print ("ID before passing:", id(var))
testfunction(var)
print ("list after function call", var)

它将生成以下 output

It will produce the following output

ID before passing: 2716006372544
Inside function: [10, 20, 30, 40]
ID inside the function: 2716006372544
list after function call [10, 20, 30, 40, 100]

Python Function Arguments

函数参数是在调用函数时传递给函数的值或变量。函数的行为通常取决于传递给它的参数。

Function arguments are the values or variables passed into a function when it is called. The behavior of a function often depends on the arguments passed to it.

在定义函数时,您在括号内指定变量列表(称为形式参数)。这些参数充当在调用函数时将传递给该函数的数据的占位符。当调用函数时,必须为每个形式参数提供值。这些称为实际参数。

While defining a function, you specify a list of variables (known as formal parameters) within the parentheses. These parameters act as placeholders for the data that will be passed to the function when it is called. When the function is called, value to each of the formal arguments must be provided. Those are called actual arguments.

function arguments

Example

让我们修改 greetings 函数,并将 name 设置为参数。作为实际参数传递给函数的字符串将在函数内变成 name 变量。

Let’s modify greetings function and have name an argument. A string passed to the function as actual argument becomes name variable inside the function.

def greetings(name):
   "This is docstring of greetings function"
   print ("Hello {}".format(name))
   return

greetings("Samay")
greetings("Pratima")
greetings("Steven")

此代码将生成以下输出:

This code will produce the following output −

Hello Samay
Hello Pratima
Hello Steven

Types of Python Function Arguments

根据在定义 Python 函数时声明参数的方式,它们被归类为以下类别:

Based on how the arguments are declared while defining a Python function, they are classified into the following categories −

Positional or Required Arguments

必需参数是按正确的位置顺序传递给函数的参数。在这里,函数调用中的参数数量应与函数定义完全匹配,否则代码会给出一个语法错误。

Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition, otherwise the code gives a syntax error.

Example

在下面的代码中,我们调用函数 printme(),不带任何参数,这将产生错误。

In the code below, we call the function printme() without any parameters which will give error.

# 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()

执行上述代码后,将生成以下结果 −

When the above code is executed, it produces the following result −

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

Keyword Arguments

关键字参数与函数调用相关。当您在函数调用中使用关键字参数时,调用者通过参数名称识别参数。这允许您跳过参数或将它们置于顺序之外,因为 Python 解释器能够使用提供的关键字将值与参数匹配。

Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters.

Example 1

以下示例展示了如何在 Python 中使用关键字参数。

The following example shows how to use keyword arguments in 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")

执行上述代码后,将生成以下结果 −

When the above code is executed, it produces the following result −

My string

Example 2

以下示例给出了更加清晰的图片。请注意,参数的顺序无关紧要。

The following example gives more clear picture. Note that the order of parameters does not matter.

# 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" )

执行上述代码后,将生成以下结果 −

When the above code is executed, it produces the following result −

Name:  miki
Age  50

Default Arguments

默认参数是指如果在函数调用中未为该参数提供值,则假定该参数的默认值。

A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument.

Example

以下示例给出了有关默认参数的思路,如果未传递默认年龄,则打印默认年龄:

The following example gives an idea on default arguments, it prints default age if it is not passed −

# 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" )

执行上述代码后,将生成以下结果 −

When the above code is executed, it produces the following result −

Name:  miki
Age  50
Name:  miki
Age  35

Positional-only arguments

那些只能通过它们在函数调用中的位置来指定的参数被称为仅限位置的参数。它们是通过在函数的参数列表中所有仅限位置的参数后面放置“/”来定义的。此功能是随着 Python 3.8 的发布而引入的。

Those arguments that can only be specified by their position in the function call is called as Positional-only arguments. They are defined by placing a "/" in the function’s parameter list after all positional-only parameters. This feature was introduced with the release of Python 3.8.

使用此类型的参数的好处是,它确保以正确的顺序使用正确的参数来调用函数。仅限位置的参数应作为位置参数传递给函数,而不是关键字参数。

The benefit of using this type of argument is that it ensures the functions are called with the correct arguments in the correct order. The positional-only arguments should be passed to a function as positional arguments, not keyword arguments.

Example

在以下示例中,我们定义了两个仅限位置的参数,即“x”和“y”。此方法应按声明参数的顺序使用位置参数调用,否则,我们将收到错误。

In the following example, we have defined two positional-only arguments namely "x" and "y". This method should be called with positional arguments in the order in which the arguments are declared, otherwise, we will get an error.

def posFun(x, y, /, z):
    print(x + y + z)

print("Evaluating positional-only arguments: ")
posFun(33, 22, z=11)

它将生成以下 output

It will produce the following output

Evaluating positional-only arguments:
66

Keyword-only arguments

那些必须在调用函数时按其名称指定的参数称为仅限关键字的参数。它们是通过在函数的参数列表中任何仅限关键字的参数之前放置星号(“*”)来定义的。此类型的参数只能作为关键字参数传递给函数,而不是位置参数。

Those arguments that must be specified by their name while calling the function is known as Keyword-only arguments. They are defined by placing an asterisk ("*") in the function’s parameter list before any keyword-only parameters. This type of argument can only be passed to a function as a keyword argument, not a positional argument.

Example

在下面的代码中,我们定义了一个带有三个仅限关键字参数的函数。要调用此方法,我们需要传递关键字参数,否则,我们将遇到错误。

In the code below, we have defined a function with three keyword-only arguments. To call this method, we need to pass keyword arguments, otherwise, we will encounter an error.

def posFun(*, num1, num2, num3):
    print(num1 * num2 * num3)

print("Evaluating keyword-only arguments: ")
posFun(num1=6, num2=8, num3=5)

它将生成以下 output

It will produce the following output

Evaluating keyword-only arguments:
240

Arbitrary or Variable-length Arguments

可能需要为某个函数处理比函数定义时指定的参数更多的参数。这些参数称为可变长参数,并且与必需参数和默认参数不同,它们在函数定义中没有名称。

You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.

具有非关键词可变参数的函数的语法如下 −

Syntax for a function with non-keyword variable arguments is this −

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

一个星号 (*) 放在变量名前面,该变量保存所有非关键词可变参数的值。如果在函数调用期间未指定任何其他参数,则此元组将保持为空。

An asterisk (*) is placed before the variable name that holds the values of all non-keyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call.

Example

以下是 Python 可变长参数的一个简单示例。

Following is a simple example of Python variable-length arguments.

# 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 )

执行上述代码后,将生成以下结果 −

When the above code is executed, it produces the following result −

Output is:
10
Output is:
70
60
50

在下一章中,我们将详细讨论这些函数参数。

In the next few chapters, we will discuss these function arguments at length.

Order of Python Function Arguments

函数可以具有上面定义的任何类型的参数。但是,必须按以下顺序声明参数:

A function can have arguments of any of the types defined above. However, the arguments must be declared in the following order −

  1. The argument list begins with the positional-only args, followed by the slash (/) symbol.

  2. It is followed by regular positional args that may or may not be called as keyword arguments.

  3. Then there may be one or more args with default values.

  4. Next, arbitrary positional arguments represented by a variable prefixed with single asterisk, that is treated as tuple. It is the next.

  5. If the function has any keyword-only arguments, put an asterisk before their names start. Some of the keyword-only arguments may have a default value.

  6. Last in the bracket is argument with two asterisks ** to accept arbitrary number of keyword arguments.

下图显示了形式参数的顺序:

The following diagram shows the order of formal arguments −

order of formal arguments

Python Function with Return Value

函数定义中最后一个语句作为 return 关键字表示函数块的结束,并且程序流返回到调用函数。尽管块中最后一个语句之后的缩进减少也意味着返回,但使用显式返回是一种良好的做法。

The return keyword as the last statement in function definition indicates end of function block, and the program flow goes back to the calling function. Although reduced indent after the last statement in the block also implies return but using explicit return is a good practice.

除了流程控制之外,函数还可向调用函数返回值。已返回表达式的值可以存储在变量中以进行进一步处理。

Along with the flow control, the function can also return value of an expression to the calling function. The value of returned expression can be stored in a variable for further processing.

Example

让我们定义 add() 函数。它将传递给它的两个值相加,并返回加法。返回的值存储在名为 result 的变量中。

Let us define the add() function. It adds the two values passed to it and returns the addition. The returned value is stored in a variable called result.

def add(x,y):
   z=x+y
   return z
a=10
b=20
result = add(a,b)
print ("a = {} b = {} a+b = {}".format(a, b, result))

它将生成如下输出:

It will produce the following output −

a = 10 b = 20 a+b = 30

The Anonymous Functions

当函数不是通过使用 def 关键字以标准方式声明时,这些函数称为匿名函数。相反,它们是使用 lambda 关键字定义的。

The functions are called anonymous when they are not declared in the standard manner by using the def keyword. Instead, they are defined using the lambda keyword.

  1. Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.

  2. An anonymous function cannot be a direct call to print because lambda requires an expression

  3. Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.

  4. Although it appears that lambda’s are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons.

Syntax

lambda 函数的语法仅包含一个语句,如下所示 −

The syntax of lambda functions contains only a single statement, which is as follows −

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

Example

以下示例演示函数的 lambda 形式如何工作 −

Following is the example to show how lambda form of function works −

# 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 ))

执行上述代码后,将生成以下结果 −

When the above code is executed, it produces the following result −

Value of total :  30
Value of total :  40

Scope of Variables

程序中的所有变量可能无法在该程序的所有位置访问。这取决于变量的声明位置。

All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.

scope of a variable 确定可以在其中访问特定标识符的程序部分。Python 中变量有两个基本范围 −

The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python −

  1. Global variables

  2. Local variables

Global vs. Local variables

在函数主体内部定义的变量具有局部范围,而在函数外部定义的变量具有全局范围。

Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.

这意味着仅可以在声明它们的函数内访问局部变量,而可以在整个程序体中通过所有函数访问全局变量。当调用函数时,将在其中引入声明的变量。

This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.

Example

以下是局部范围和全局范围的一个简单示例 −

Following is a simple example of local and global scope −

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)

执行上述代码后,将生成以下结果 −

When the above code is executed, it produces the following result −

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