Have you ever thought, “I wish Python had a function that did ________.” Fill in the blank. If so, I have great news! Python gives you the ability to create your own custom functions. There are a few things you need to understand, but it’s not that hard to do. So let’s get started.
您是否曾经想过:“我希望Python的功能可以做到________。” 填空。 如果是这样,我有个好消息! Python使您能够创建自己的自定义函数。 您需要了解一些事情,但这并不难。 因此,让我们开始吧。
Custom functions are a great way to nicely package reusable blocks of code. At the most basic level, a custom function requires only five components:
自定义函数是很好地打包可重用代码块的好方法。 在最基本的级别上,自定义功能仅需要五个组件:
Use the def keyword to begin the function definition.
使用def关键字开始函数定义。
Name your function. 命名您的功能。Supply one or more parameters. Actually parameters are optional, but the parentheses are not. Followed by a colon.
提供一个或多个参数。 实际上,参数是可选的,但括号不是。 其次是冒号。
Enter lines of code that make your function do whatever it does. Enter the code where the # logic here is shown in the sample code below.
输入使您的函数执行其功能的代码行。 输入代码,此处的#逻辑在下面的示例代码中显示。
Use the return keyword at the end of the function to return the output. This is also optional. If omitted, the function will return None. 在函数末尾使用return关键字可返回输出。 这也是可选的。 如果省略,该函数将返回None。 def function_name (parameter_one, parameter_two, parameter_n): # logic here returnAs you can see, the bare bones of a function are simple. Let’s stop playing with the theoretical though and create an actual function.
如您所见,函数的基本内容很简单。 让我们停止使用理论,而是创建一个实际函数。
Every function needs a name. Otherwise, you have no way to reference it in your code when you need to use it. Name your function something intuitive. If the purpose of your function is to sum all the numbers you send into it via the parameter list, name it add_nums() or sum_the_numbers(). Do not name it s() or function1(). These last two are poor choices. Remember, code is read by humans.
每个功能都需要一个名称。 否则,当您需要使用它时,您将无法在代码中引用它。 用直观的方式命名函数。 如果函数的目的是对通过参数列表发送给它的所有数字求和,则将其命名为add_nums()或sum_the_numbers() 。 不要将其命名为s()或function1()。 最后两个是错误的选择。 请记住,代码是人类读取的。
Also, the function name must be followed by a set of parentheses. If you don’t need any parameters, the parentheses will be empty, but they must present. Then finish the definition line with a colon. The colon indicates any indented lines below this one are part of the function.
此外,函数名称后必须带有一组括号。 如果不需要任何参数,括号将为空,但必须存在。 然后用冒号结束定义线。 冒号表示该行下方的任何缩进线都是该功能的一部分。
def sum_the_numbers ():Once you name your function, decide the required parameters. Parameters, or arguments, are used to pass pertinent data to your function. How many numbers can the function add together? If no parameters are supplied, will default values be used? What’s the order of the arguments?
命名函数后,请确定所需的参数。 参数或参数用于将相关数据传递给函数。 函数可以将几个数字相加? 如果未提供任何参数,是否将使用默认值? 参数的顺序是什么?
Parameters are inserted between the parentheses following the function name. They are separated by commas. Again, use intuitive names so you can easily recall the purpose of each parameter.
在函数名称后的括号之间插入参数。 它们之间用逗号分隔。 同样,请使用直观的名称,以便您轻松回忆每个参数的用途。
If our function will only add two numbers, we can create two parameters, num1 and num2. If we change the function to add three numbers, we can add a third parameter, num3.
如果函数仅将两个数字相加,则可以创建两个参数num1和num2 。 如果我们更改函数以添加三个数字,则可以添加第三个参数num3 。
def sum_the_numbers (num1, num2):If you choose to assign default values for the parameters, just replace the current parameter names with num1=0 and num2=0. The 0 should be replaced by whatever default value you want to assign.
如果选择为参数分配默认值,只需将当前参数名称替换为num1 = 0和num2 = 0即可。 0应该替换为您想要分配的默认值。
def sum_the_numbers (num1 = 0, num2 = 0):Typically, when you execute a function, you’ll call it using a line of code similar to sum_the_numbers (5, 3). By supplying default values, you can omit one or more of the parameters from the execution line of code, and the function will still run, only using the default values.
通常,执行函数时,将使用类似于sum_the_numbers(5,3)的代码行来调用它。 通过提供默认值,您可以从代码执行行中省略一个或多个参数,并且该函数仍将运行,仅使用默认值即可。
Now let’s add some logic to the function. This is what makes the function add the numbers. This section may be short if you are performing a simple task, like adding two numbers together. Or you could have hundreds of lines of code in this portion for a more complex undertaking. Remember, all lines of code included as part of the function must be indented like the total = num1 + num2 line below.
现在让我们向函数添加一些逻辑。 这就是使函数加数字的原因。 如果您要执行简单的任务(例如将两个数字加在一起),则本节可能会很短。 或者,您可以在此部分中包含数百行代码来完成更复杂的任务。 请记住,函数中包含的所有代码行都必须缩进,例如下面的total = num1 + num2行。
def sum_the_numbers (num1 = 0, num2 = 0): total = num1 + num2Now that your code has completed its prescribed work, you may or maybe not need to return a value to the process that called your function. If you do not need to return a value, you may omit the return statement. However, in this example function, we need to return the sum. The line is return total.
现在您的代码已完成其规定的工作,您可能需要或可能不需要将值返回给调用函数的过程。 如果不需要返回值,则可以省略return语句。 但是,在此示例函数中,我们需要返回总和。 这行是总回报。
def sum_the_numbers (num1 = 0, num2 = 0): total = num1 + num2 return totalThe return statement sends the value stored in total back to the section of code where this function was executed. You will usually have a variable present to store the returned value. For example, summation = sum_the_numbers (5, 3). The value returned by the function will be stored in the summation variable. Now that we have all the necessary components for our function to succeed, let see how we execute it in a code segment.
return语句将总计存储的值发送回执行此函数的代码部分。 通常,您将有一个变量来存储返回的值。 例如, sumsum = sum_the_numbers(5,3) 。 函数返回的值将存储在求和变量中。 现在,我们拥有使函数成功运行所需的所有必要组件,让我们看看如何在代码段中执行它。
Whenever we execute a user-defined function, we use the name of the function with any required parameters. If the function returns a value, we usually will do something with its output. We may print it, store it in a variable, or send it into another function. Assuming we are going to store the output in a variable, our function execution may look something like the code below.
每当执行用户定义的函数时,我们都将函数名称与任何必需的参数一起使用。 如果函数返回一个值,我们通常会对其输出做一些事情。 我们可能会打印它,将其存储在变量中,或将其发送到另一个函数中。 假设我们将输出存储在变量中,则函数执行可能类似于下面的代码。
summation = sum_the_numbers (10, 5)If we choose to print the returned value straight to the screen, we can use this code instead.
如果选择直接将返回值打印到屏幕上,则可以使用此代码。
print(sum_the_numbers (10, 5))Remember, when you call your function the arguments must be supplied in the same order you’ve listed them in the function definition, num1 followed by num2. However, if you’ve forgotten the order you can change it up as long as you specify the argument keywords when executing the function. When using argument keywords, the command will look similar to sum_the_numbers (num2=5, num1=10).
请记住,在调用函数时,必须按照在函数定义中列出参数的顺序提供参数,顺序为num1和num2 。 但是,如果您忘记了顺序,则只要在执行函数时指定参数关键字,就可以更改顺序。 使用自变量关键字时,该命令看起来类似于sum_the_numbers(num2 = 5,num1 = 10) 。
summation = sum_the_numbers (num2=5, num1=10)I’m sure you can already see an issue with our design. Every time we wish to add more numbers, we are required to add another parameter. But there is a way to handle an endless number of parameters in your function. Instead of listing each parameter name between the parentheses in the function definition, use the *args technique.
我确定您已经看到我们设计的问题。 每次我们希望添加更多数字时,都需要添加另一个参数。 但是有一种方法可以处理函数中无数个参数。 而不是在函数定义的括号之间列出每个参数名称,请使用* args技术。
def sum_the_numbers (*args): total = 0 for num in args: total += num return totalWhen an * proceeds a parameter name, it indicates any number of parameters may be passed into the function. This will create a list of the parameter values. You simply unpack the args list in the function. This small change in our function has made it much more versatile.
当*表示参数名称时,表示可以将任意数量的参数传递给函数。 这将创建一个参数值列表。 您只需在函数中解压缩args列表即可。 我们功能的微小变化使其功能更加丰富。
Often, the user-defined function and the code executing it are in the same Python script. In our example, the whole script would look like this one.
通常,用户定义函数和执行该函数的代码在同一Python脚本中。 在我们的示例中,整个脚本看起来像这样。
def sum_the_numbers (*args): # define our function total = 0 # set initial total to zero for num in args: # loop through each value total += num # add each value to the total return total # return the summed total summation = sum_the_numbers(5, 10) # execute our function print(summation) # print the totalStandard user-defined functions are straight forward to use, but a very powerful tool for a developer. Of course, user-defined functions do not stop with this standard approach. If you were buying something online or from a late-night infomercial, you’d expect to get even more for your $19.95. The same is true with user-defined functions.
标准的用户定义函数可以直接使用,但是对于开发人员来说是非常强大的工具。 当然,用户定义的功能不会因这种标准方法而停止。 如果您是在网上购买商品或从深夜的电视购物中购买商品,则您期望以19.95美元的价格获得更多。 用户定义的函数也是如此。
If you like the standard user-defined function, you’ll love anonymous user-defined functions. These functions are written inline, where you need them, without a name, and without proper definition syntax. These functions are also referred to as comprehensions or lambda functions.
如果您喜欢标准的用户定义函数,则将喜欢匿名用户定义函数。 这些函数是内联编写的,在需要它们的地方,没有名称,也没有正确的定义语法。 这些功能也称为理解功能或lambda函数。
For this example, pretend our scenario is the same as above. We need a function capable of add two numbers together. Instead of our sum_the_numbers function, we can use a lambda function.
对于此示例,假设我们的场景与上述相同。 我们需要一个能够将两个数字相加的函数。 代替我们的sum_the_numbers函数,我们可以使用lambda函数。
answer = lambda num1, num2: num1 + num2 print(answer(5, 10))Lambda is the Python keyword used to define these functions instead of def. Therefore, they are often referred to as lambda functions.
Lambda是用于定义这些函数的Python关键字,而不是def 。 因此,它们通常被称为lambda函数。
In this example of our lambda function, we defined the variable answers as the function itself. Then we simply pass in the needed parameters when we refer to the variable name. The result is an anonymous function disguised as a dynamic variable.
在我们的lambda函数的示例中,我们将变量answer定义为函数本身。 然后,当我们引用变量名称时,我们只需传递所需的参数。 结果是伪装成动态变量的匿名函数。
In short, the syntax for anonymous functions is lambda argument_list: expression.
简而言之,匿名函数的语法为lambda arguments_list:expression 。
Let’s take our example one step further and pretend the scenario begins with a list of numbers. We need to create a new list of numbers by squaring every number from our first list. We could create a standard user-defined function to accomplish this as we did above. But instead, we decide to use an anonymous function.
让我们进一步举例说明,假设场景以数字列表开始。 我们需要通过平方第一个列表中的每个数字来创建一个新的数字列表。 我们可以像上面一样创建一个标准的用户定义函数来完成此任务。 但是,我们决定使用匿名函数。
In order to iterate through the list, we use Python’s map function. The map function takes two arguments. The first one is a function. In this case, it will be an anonymous function. The second parameter is some iterable data, like the list of numbers we want to square. The map function will take each item in the iterable, run it through the specified function, and append the output to a new iterable data structure.
为了遍历列表,我们使用Python的map函数。 map函数带有两个参数。 第一个是函数。 在这种情况下,它将是一个匿名函数。 第二个参数是一些可迭代的数据,例如我们要平方的数字列表。 map函数将把可迭代项中的每个项都放入,通过指定的函数运行它,并将输出附加到新的可迭代数据结构中。
numbers = [1,2,3,4,5] squared_numbers = list(map(lambda number: number ** 2, numbers))The list() function in this code converted the map function’s default iterable output, a map object, to a Python list. List’s are much easier to use throughout the rest of our code.
此代码中的list()函数将map函数的默认可迭代输出(map对象)转换为Python列表。 在我们其余的代码中,列表的使用要容易得多。
Again, you can see our lambda code is relatively short compared to the standard approach used below.
同样,您可以看到我们的lambda代码与下面使用的标准方法相比相对较短。
def square_the_numbers (numbers_to_square): the_squared_numbers = [] for number in numbers_to_square: the_squared_numbers.append(number ** 2) return the_squared_numbers numbers = [1,2,3,4,5] squared_numbers = square_the_numbers(numbers)Commit the time necessary to learn how to implement user-defined functions in Python. They are powerful. They create reusable blocks of code. They help organize your code. And they are absolutely necessary if you begin using object-oriented programming techniques. User-defined functions are a necessary tool in the modern developer’s repertoire.
花费时间学习如何在Python中实现用户定义的函数。 他们很强大。 他们创建可重用的代码块。 他们帮助组织您的代码。 如果您开始使用面向对象的编程技术,那么它们是绝对必要的。 用户定义的功能是现代开发人员的必备工具。
翻译自: https://towardsdatascience.com/how-to-create-user-defined-functions-in-python-e5a529386534
