Home  >  Article  >  Backend Development  >  Python Programming: Basic Guidelines About Function Return Values ​​and Best Practices

Python Programming: Basic Guidelines About Function Return Values ​​and Best Practices

王林
王林forward
2023-04-10 11:31:051511browse

As the last article on the topic of functions, this article will introduce function return values ​​and some basic best practice guidelines for writing functions.

Function output: return value

The return value of a function is one of the things that puts Python ahead of its competitors. In most other languages, functions are usually only allowed to return an object, but in Python you can return a tuple - which means anything you want can be returned. This feature allows programmers to write software that is much more difficult, or certainly more tedious, to write in other languages. We have already said that to return something from a function we need to use the return statement followed by the thing we want to return. There can be multiple return statements in the function body as needed.

On the other hand, if in the function body we don't return anything, or we call a "naked" return statement, the function will return None. This behavior is harmless when not needed, but it also allows you to work out some interesting patterns, confirming that Python is a very consistent language.

We say it's harmless because you are never forced to collect the results of a function call. The following will show you what I mean through an example:

# 返回none值
def func():
pass

func() # 这个调用是没有接收的,将丢失
a = func() # 这个调用被a接收
print(a) # prints: None

Note that the entire function body only consists of pass statements. As the official documentation tells us, pass is a no-op because when it is executed, nothing happens. It is useful as a placeholder when a statement is syntactically required but does not require execution of the code. In other languages, we might just express this with a pair of curly braces ({}), which defines an empty scope; but in Python, scopes are defined by indented code, so statements like pass necessary.

Also note that the first call to func() returns a value that was not received (None). As we mentioned earlier, it is not necessary to receive the return value of a function call.

This is nice, but not very interesting, how about we write a fun function? Remember we discussed the factorial function. Let's write our own implementation here (for simplicity, we assume that the function is always called correctly with the appropriate values, so we don't need to check the input parameters):

# 阶乘函数,返回单个值
def factorial(n):
if n in (0, 1):
return 1
result = n
for k in range(2, n):
result *= k
return result

f5 = factorial(5) # f5 = 120

Note that we have two return points . If n is 0 or 1, then 1 is returned. Otherwise, we perform the required calculations and return the result.

Tip: In Python, it is common to use the in operator for member checking, like we did in the previous example, rather than the more verbose check:

if n == 0 or n == 1:

Now try to write this function more concisely:

# 返回单个值示例.2
from functools import reduce
from operator import mul

def factorial2(n):
return reduce(mul, range(1, n + 1), 1)

f5 = factorial(5) # f5 = 120

This is simple The example shows how Python can be both elegant and concise. This implementation is readable even though we have never seen reduce() or mul(). If you can't read or understand it, take a few minutes to do some Python documentation research until you understand its behavior. Being able to find functions in documentation and understand code written by others are tasks that every developer needs to be able to perform, so make it a challenge.

Tip: Learn to view the help that comes with Python. Make sure to look for the help() function, which is very useful when exploring using the console.

Returning Multiple Values

As we mentioned earlier, unlike most other languages, Python makes it very easy to return multiple objects from a function. This feature opens up endless possibilities and allows you to code in a style that is difficult to reproduce in other languages. Our thinking is limited by the tools we use. So when Python gives you more freedom than other languages, it's enhancing your creative abilities.

Returning multiple values ​​is very simple: just use tuples (explicit or implicit). Let's look at a simple example that mimics the divmod() built-in function:

# 返回多个值
def moddiv(a, b):
return a // b, a % b

print(moddiv(20, 7)) # prints (2, 6)

We could wrap the bold portion of the previous code in parentheses to make it an explicit tuple, but there is no need to do so. The above function returns both the result of division and the remainder.

Helpful advice about functions

When writing functions, it is very useful to follow some best practice guidelines so that you can write the function well. Let's take a look at these guidelines to help you better understand and apply functions.

1) A function should only do one thing

A function that does one thing is easy to describe in one sentence. Functions that perform multiple tasks can be refactored into smaller functions that perform one task. These smaller functions are generally easier to read and understand.

2) Functions should be small

The smaller they are, the easier it is to test and write them, so they are more focused on doing one thing .

3) The fewer input parameters the better

Functions that accept a large number of parameters quickly become unmanageable (among other problems). When more input parameters are required, consider as appropriate, such as refactoring into class objects or other composite data.

4) The return value of the function should be consistent

Returning False and returning None are not the same thing, even in a Boolean context, their values ​​are False. False means we have information (i.e. False), while None means there is no information. Whenever possible, write functions that return in a consistent manner regardless of what's going on in their logic.

5)函数不应该有副作用

换句话说,函数不应该影响调用它们的值。这可能是目前最难理解的一条实践性原则,所以这里给出一个使用列表的示例。在下面的代码中,注意如何不使用sorted()函数对numbers进行排序,该函数实际上返回的是已排序的数字副本。相反,list.sort()方法作用于numbers对象本身,这很好,因为它是一个方法(属于对象的函数,因此有权修改它):

>>> numbers = [4, 1, 7, 5]
>>> sorted(numbers) # 不会排序原始的'numbers' 数字列表
[1, 4, 5, 7]
>>> numbers # 验证一下
[4, 1, 7, 5] # 很好,没有改变原始数据对象
>>> numbers.sort() # 这将实质性影响原始列表
>>> numbers
[1, 4, 5, 7]

所以,遵循以上这些常规的基本指导原则,将有益于你写出更好的函数,为你实现更好的服务。

本文小结

到此关于Python函数的主体性知识就介绍完了——函数定义语法、输入参数定义以及相关规则、返回值实现和多返回值等,并简单总结了基于最佳实践的一些有益基本指导原则。请多加练习和体会,以便更好的理解和掌握作为Python的核心特性之一的函数。

The above is the detailed content of Python Programming: Basic Guidelines About Function Return Values ​​and Best Practices. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete