函数参数(以 Python 为例)

发布于 2024-11-29 20:18:11 字数 781 浏览 2 评论 0原文

什么是[函数]参数?它们的用途是什么?
我最近开始学习Python;我是编程新手,对于这个基本问题我深表歉意。

在我浏览的每个 Python 教程中,他们都会谈论参数。  我一直在寻找这个问题的答案,并找到了很多答案,但它们对我来说有点难以理解。我可能只是缺少一些概念背景。
那么...当我定义一个函数时,括号里的东西是用来做什么的? 示例:

def hi( This is the part that i dont get):
     print 'hi'

编辑:
与此相关的两个后续问题后来被关闭并合并在这里,因此某些答案具有部分脱离上下文的特征。
后续问题是: [释义]

What are [function] arguments? What are they used for?
I started learning Python very recently; I'm new to programming and I apologize for this basic question.

In every Python tutorial I go through they talk about arguments.  I have looked for the answer to this question and have found many answers but they are just a little too hard for me to understatnd. I may just be missing some conceptual background.
So... when I define a function, what are the things in parenthesis used for?
Example:

def hi( This is the part that i dont get):
     print 'hi'

Edit:
Two follow-up questions related to this one were later closed and merged here, hence the partial out-of-context trait of some of the answers.
The follow-up questions were: [paraphrased]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

梦醒灬来后我 2024-12-06 20:18:11

简而言之,它们是“传递到”函数以告诉它要做什么的数据。维基百科有详细信息。

http://en.wikipedia.org/wiki/Function_argument

例如,您的 hi () 函数可能需要知道向谁打招呼:

def hi(person):
    print "Hi there " + person + ", how are you?"

或者数学函数可能需要一个要运算的值:

def square(x):
     return x * x

In a few words, they're data that gets "passed into" the function to tell it what to do. Wikipedia has details.

http://en.wikipedia.org/wiki/Function_argument

For instance, your hi() function might need to know who to say hello to:

def hi(person):
    print "Hi there " + person + ", how are you?"

Or a mathematical function might need a value to operate on:

def square(x):
     return x * x
ヅ她的身影、若隐若现 2024-12-06 20:18:11

这不是一个Python问题,而是一个通用的编程问题。一个非常基本的。


在回答有关参数的问题之前,并考虑到您提出的其他问题,讨论变量的概念是很有用的。
变量是一块命名的内存,可以在其中存储和检索底层程序感兴趣的信息。换句话说,它是一个由程序员选择的与其内容相关联的符号名称。使用通常称为赋值的各种语言结构,程序员可以读取或写入变量的内容。
需要注意的是,在编写程序时不需要定义变量的值(即内容)。仅在运行时才需要。这允许程序描述要对符号元素执行的操作,而无需确切知道这些元素具有的值。考虑这个片段,它是一个更大程序的一部分:

# ... some logic above
ball_volume = 4.0 / 3 * math.pi * ball_radius
if ball_volume > 200:
   print ("Man, that's a big ball")
# ... more logic below

在编写程序时,不需要知道 ball_radius 的实际值;然而,假设该变量将包含某个假设球的数值,该代码片段能够描述如何计算球的体积。以这种方式,当程序运行时,并且不知何故(稍后详细介绍)ball_radius 变量已被初始化为一些适当的值,变量 ball_volume 也可以被初始化和使用,这里在条件中语句(if),并且可能在下面。 (在某些时候,变量可能会超出范围,但是控制程序何时可以访问特定变量的概念远远超出了本入门知识的范围)。
在某些语言中,可能与特定变量关联的数据类型需要显式定义并且不能更改。例如,某些变量只能保存整数值,其他变量只能保存字符串值(文本)等。在Python中没有这样的限制,可以将变量分配和重新分配给任何类型的数据,但是当然,程序员需要例如,跟踪这一点以避免将一些文本数据传递给数学函数。

存储在变量内的数据可能来自非常不同的来源。教程和介绍性文档中提供的许多示例都具有来自键盘输入的数据(就像在某些问题中提到的使用 raw_input 时一样)。这是因为它允许人们尝试这些教程片段进行交互式测试。但是,如果变量仅从交互式用户输入中获取数据,则程序的有用性将相当有限。还有许多其他来源,这就是编程如此强大的原因:可以使用以下数据来初始化变量:

  • 数据库
  • 文本文件或文件 各种文本格式(XML、JSON、CSV..)
  • 各种格式的二进制文件
  • 互联网连接
  • 物理设备:相机、温度传感器...

简而言之,参数,也称为参数是传递给函数的变量,[通常]用于提供与函数不同的输出和行为功能。例如:

>>> def say_hello(my_name):
...    print("Hello,", my_name, "!")

>>> say_hello("Sam")
Hello, Sam !
>>> customer_name = "Mr Peter Clark"    #imagine this info came from a database
>>> # ...
>>> say_hello(customer_name)
Hello, Mr Peter Clark !
>>>

在上面的例子中,my_name就像say_hello函数的任何局部变量一样;这允许函数定义在运行时调用函数时它将如何处理基础值。
在运行时,可以使用立即值(逻辑中“硬编码”的值,例如示例中的“Sam”)或[值of]另一个变量(例如customer_name)。在这两种情况下,函数的 my_name 变量的值都会被分配一些值,分别为“Sam”和“Mr Peter Clark”。在后一种情况下,该值是 customer_name 变量包含的任何值。请注意,函数内部使用的变量的名称 (my_name) 以及调用函数时的变量名称 (customer_name) 不需要是相同的。 (这些分别称为“形式参数”和“实际参数”)

请注意,虽然通常大多数参数都作为输入传递给函数,但在某些情况下条件下,它们可以用作输出,即在调用函数的逻辑级别提供新的/修改的值。这样做需要隐式或显式地使用正确的调用约定规范(请参阅下面的参数传递约定


现在...除了对参数用途的基本理解之外,事情变得比这更复杂一些(但也不复杂)。我将一般性地讨论这些附加概念,并说明它们在 Python 中的应用。

参数的默认值(又名“可选”参数)
当函数声明时,它可以指定某些参数的默认值。这些值用于调用函数时未指定的参数。由于显而易见的原因,这些可选参数位于参数列表的末尾(否则语言编译器/解释器可能很难确定哪个参数是哪个......)

>>> def say_hello(dude = "Sir"):
...     print("Hello,", dude, "!")
...
>>> say_hello()
Hello, Sir !
>>> say_hello("William Gates")
Hello, Bill !            #just kidding ;-)
Hello, William Gates !   # but indeed. works as the original function when param
                         # is specified

参数数量可变
在某些情况下,定义一个函数以便它可以接受可变数量的参数可能会很方便。虽然此类参数值列表最终在某种容器(列表、数组、集合...)中传递,但各种语言提供了访问此类参数值的便捷方法。

>>> def add_many(operand1, *operands):
...    Sum = operand1
...    for op in operands:
...       Sum += op
...    return Sum
...
>>> add_many(1, 3, 5, 7, 20)
36
>>> add_many(1, 3)
4

命名参数(关键字参数)
使用 Python 和其他一些语言,可以在调用函数时显式命名参数。默认情况下,参数传递是基于位置基础的(“第一个参数、第二个参数等),Python 将允许你命名参数并以任意顺序传递它们。这主要是一个语法细节,但与接受大量参数的函数的默认参数也是一个很好的自记录功能,

>>> def do_greetings(greeting, person):
...    print (greeting, "dear", person, "!")
...
>>> do_greetings(person="Jack", greeting="Good evening")
Good evening dear Jack !

例如,使用 do_greetingsas-is ,您甚至可以传递一个字典,例如:

>>> my_param_dict = {"greeting":"Aloha", "person":"Alan"}

>>> do_greetings(**my_param_dict)
Aloha dear Alan !

最后,虽然传递参数的奇特方式以及处理可变数量参数的方法的能力是各种语言的有用功能,但需要提及两个关键概念:

参数传递约定:按值或按参考
到目前为止,我们使用的所有函数都没有改变传递给它们的参数的值。我们可以想象,在很多情况下,函数可能想要执行此操作,要么对所述值执行一些转换或计算,以供其内部使用,要么有效地更改变量的值,以便在级别上反映更改调用该函数的逻辑。这就是参数传递约定派上用场的地方......
按值传递的参数可能会被函数更改以进行其内部计算,但不会在调用方法的级别上更改。
通过引用传递的参数将反映在调用方法级别对它们所做的更改。
每种语言都指定了参数传递的方式。典型的约定是按值传递整数、数字值和其他基本类型,并按引用传递对象。大多数语言还提供允许更改其默认约定的关键字。

在Python中,所有参数都是通过引用传递的。然而,一些变量类型是不可变的(数字、字符串、元组...),因此它们不能被函数更改。

类方法的隐式“self”或“this”参数
在面向对象的语言中,方法(即类中的函数)接收一个额外的参数,该参数是底层对象(类的实例)的值,允许该方法在其计算中使用该类的各种属性成员和/或改变其中一些属性的值。

在 Python 中,此参数在方法定义级别声明,但隐式传递。被声明后,它可以被命名为几乎任何人想要的名字,尽管按照惯例,这通常被称为self

>>> class Accumulator:
...   def __init__(self, initialValue = 0):
...        self.CurValue = initialValue
...   def Add(self, x):
...        self.CurValue += x
...        return self.CurValue
...
>>> my_accu = Accumulator(10)
>>> my_accu.Add(5)
15
>>> my_accu.Add(3)
18

This is not a Python question, but rather a generic programming question. A very basic one.


Before answering the question about arguments, and in view of the other questions you asked, it is useful to discuss the concept of variables.
A variable is a named piece of memory where information of interest to the underlying program can be stored and retrieved. In other words, it is a symbolic name, chosen by the programmer, that is associated to its contents. Using various language constructs generally known as assignments, the programmer can read or write the contents of a variable.
It is important to note that the value (i.e. the content) of a variable needn't be defined when the program is written. It is only necessary at run-time. This allows the program to describe actions to be performed on symbolic elements without knowing exactly the value these elements have. Consider this snippet, part of a bigger program:

# ... some logic above
ball_volume = 4.0 / 3 * math.pi * ball_radius
if ball_volume > 200:
   print ("Man, that's a big ball")
# ... more logic below

At the time the program is written one doesn't need to know the actual value of ball_radius; yet, with the assumption that this variable will contain the numeric value of some hypothetical ball, the snippet is capable of describing how to compute the ball's volume. In this fashion, when the program is running, and somehow (more on this later) the ball_radius variable has been initialized with some appropriate value, the variable ball_volume can too be initialized and used, here in the conditional statement (if), and possibly below. (At some point the variable may go out-of-scope, but this concept which controls when particular variables are accessible to the program is well beyond this primer).
In some languages the type of data that may be associated with a particular variable needs to be explicitly defined and cannot change. For example some variables could hold only integer values, other variables string values (text) etc. In Python there is no such restriction, a variable can be assigned and re-assigned to any type of data, but of course, the programmer needs to keep track of this for example to avoid passing some text data to a mathematical function.

The data stored inside variable may come from very different sources. Many of the examples provided in tutorials and introductory documentation have this data coming from keyboard input (as when using raw_input as mentioned in some of your questions). That is because it allows interactive tests by the people trying out these tutorial snippets. But the usefulness of programs would be rather limited if variables only get their data from interactive user input. There are many other sources and this is what makes programming so powerful: variables can be initialized with data from:

  • databases
  • text files or files various text-base formats (XML, JSON, CSV..)
  • binary files with various formats
  • internet connections
  • physical devices: cameras, temperature sensors...

In a nutshell, Arguments, also called Parameters, are variables passed to the function which [typically] are used to provide different output and behavior from the function. For example:

>>> def say_hello(my_name):
...    print("Hello,", my_name, "!")

>>> say_hello("Sam")
Hello, Sam !
>>> customer_name = "Mr Peter Clark"    #imagine this info came from a database
>>> # ...
>>> say_hello(customer_name)
Hello, Mr Peter Clark !
>>>

In the example above, my_name is just like any local variable of the say_hello function; this allows the function to define what it will do with the underlying value when the function is called, at run-time.
At run-time, the function can be called with an immediate value (a value that is "hard-coded" in the logic, such as "Sam" in the example), or with [the value of] another variable (such as customer_name). In both cases the value of the function's my_name variable gets assigned some value, "Sam" and "Mr Peter Clark" respectively. In the latter case, this value is whatever the customer_name variable contains. Note that the names of the variables used inside the function (my_name) and when the function is called (customer_name) do not need to be the same. (these are called the "formal parameter(s)" and the "actual parameters" respectively)

Note that while typically most arguments as passed as input to a function, in some conditions, they can be used as output, i.e. to provide new/modified values at the level of the logic which called the function. Doing so requires using, implicitly or explicitly, the proper calling convention specification (See Argument passing conventions below)


Now... beyond this very basic understanding of the purpose of parameters, things get a little more complicated than that (but not much). I'll discuss these additional concepts in general and illustrate them as they apply to Python.

Default values for arguments (aka "optional" arguments)
When the function is declared it may specify the default value for some parameters. These values are used for the parameters which are not specified when the function is called. For obvious reasons these optional parameters are found at the end of the parameter list (otherwise the language compiler/interpreter may have difficulty figuring out which parameter is which...)

>>> def say_hello(dude = "Sir"):
...     print("Hello,", dude, "!")
...
>>> say_hello()
Hello, Sir !
>>> say_hello("William Gates")
Hello, Bill !            #just kidding ;-)
Hello, William Gates !   # but indeed. works as the original function when param
                         # is specified

Variable number of parameters
In some cases it may be handy to define a function so that it may accept a variable number of parameters. While such lists of parameter values ultimately get passed in some kind of container (list, array, collection...) various languages offers convenient ways of accessing such parameter values.

>>> def add_many(operand1, *operands):
...    Sum = operand1
...    for op in operands:
...       Sum += op
...    return Sum
...
>>> add_many(1, 3, 5, 7, 20)
36
>>> add_many(1, 3)
4

Named Arguments (Keyword Arguments)
With Python and a few other languages, it is possible to explicitly name the arguments when calling the function. Whereby argument passing is by default based a positional basis ("1st argument, 2nd argument etc.), Python will let you name the arguments and pass them in any order. This is mostly a syntactic nicety, but can be useful, in combination with default arguments for functions that accept very many arguments. It is also a nice self-documenting feature.

>>> def do_greetings(greeting, person):
...    print (greeting, "dear", person, "!")
...
>>> do_greetings(person="Jack", greeting="Good evening")
Good evening dear Jack !

In Python, you can even pass a dictionary in lieu of several named arguments for example, with do_greetingsas-is, imagine you have a dictionary like:

>>> my_param_dict = {"greeting":"Aloha", "person":"Alan"}

>>> do_greetings(**my_param_dict)
Aloha dear Alan !

In closing, and while the fancy ways of passing arguments, and the capability for methods to handle variable number of arguments are useful features of various languages, two key concepts need to be mentioned:

Argument passing convention : by value or by reference
So far all the functions we used didn't alter the value of the parameters passed to them. We can imagine however many instances when functions may want to do this, either to perform some conversion or computation on the said values, for its own internal use, or to effectively change the value of the variable so that the changes are reflected at the level of logic which called the function. That's where argument passing conventions come handy...
arguments which are passed by value may be altered by the function for its own internal computations but are not changed at the level of the calling method.
arguments which are passed by reference will reflect changes made to them, at the level of the calling method.
Each language specifies the ways that arguments are passed. A typical convention is to pass integers, numberic values and other basic types by value and to pass objects by reference. Most language also offer keyword that allow altering their default convention.

In python all arguments are passed by reference. However a few variables types are immutable (numbers, strings, tuples...) and they can therefore not be altered by the function.

Implicit "self" or "this" argument of class methods
In object oriented languages, methods (i.e. functions within a class) receive an extra argument that is the value of underlying object (the instance of the class), allowing the method to use various properties members of the class in its computation and/or to alter the value of some of these properties.

in Python, this argument is declared at the level of the method definition, but is passed implicitly. Being declared, it may be named most anything one wishes, although by convention this is typically called self.

>>> class Accumulator:
...   def __init__(self, initialValue = 0):
...        self.CurValue = initialValue
...   def Add(self, x):
...        self.CurValue += x
...        return self.CurValue
...
>>> my_accu = Accumulator(10)
>>> my_accu.Add(5)
15
>>> my_accu.Add(3)
18
镜花水月 2024-12-06 20:18:11

在使用参数的情况下,它只是一个关于如何使用它们的演示,而不是像您演示的那样最有效。功能非常有用。例如,如果我想添加两个数字:

def add(num1, num2):
  x = num1 + num2
  return x
add(1,3)

函数对于执行重复任务很有用,假设在您的示例中您必须向数百个名字打招呼,而不是必须执行 raw_input() 函数来读取他们的名字并向其中添加一些文本,您可以简单地调用一个函数来执行任务并传递参数(人名)。

根据你的第二个问题,参数只是传递给函数的变量,所以无论你从外部传递给它什么变量,例如我将数字 1 和 3 传递给函数内部的函数 add它们简称为num1 num2

在你的情况下,传递太多参数会产生这样的结果:

>>> add(1,2)
3
>>> add(1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add() takes exactly 2 arguments (3 given)
>>> 

祝你好运!如果您需要进一步的帮助,请随时给我发电子邮件(sbrichards (at) mit.edu)

In that case for using arguments, it is simply a demo on how to use them, not the most effective perhaps as you demonstrated. Functions are very useful. for example if i wanted to add two numbers:

def add(num1, num2):
  x = num1 + num2
  return x
add(1,3)

Functions are useful for performing repetitive tasks, let's say in your example you had to say hello to hundreds of names, instead of having to do a loop of that raw_input() function to read their name and add some text to it you could simply call a function to perform the task and pass arguments (the persons name to it).

Per your second question, arguments are just variables passed to the function, so whatever variable you pass to it from the outside, for example I pass numbers 1 and 3 to my function add on the inside of that function they are simply referred to as num1 num2.

In your case with passing too many arguments would yield this:

>>> add(1,2)
3
>>> add(1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add() takes exactly 2 arguments (3 given)
>>> 

Best of luck! and feel free to shoot me an email if you need further help (sbrichards (at) mit.edu)

辞别 2024-12-06 20:18:11

括号中的内容称为参数。基本上,这些是您希望函数使用的变量。例如,假设您有一个函数,并且您希望它在调用它时打印一个单词。通过参数,您可以定义该词的含义。这是一个例子:

def hi(word):
    print word

现在,如果我做这样的事情:

hi('Hello!')

它会打印:

'Hello!'

hi()作为名为 word 的变量传递 'Hello!',然后它打印这个词。

The stuff in the parentheses are called arguments. Basically these are variables that you want the function to work with. For example, say you have a function, and you want it to print a word when you call it. With arguments, you can define what that word will be. Here is an example:

def hi(word):
    print word

now, if I do something like this:

hi('Hello!')

it will print:

'Hello!'

hi() gets passed 'Hello!' as a variable called word, and then it prints that word.

诠释孤独 2024-12-06 20:18:11

在你的例子中,它们没有被使用。

如果你的函数需要根据你给它的参数做出不同的行为,那么参数的用途是什么。

def hi_name(name):
    print 'Hi ' + name

hi_name("John doe")

这将打印“Hi John Doe”。

现在回到函数的基础知识。

In your example they are not used.

If your function needs to behave differently depending on what arguments you give it, then what's arguments are for.

def hi_name(name):
    print 'Hi ' + name

hi_name("John doe")

This prints "Hi John Doe".

Now back to the basics about functions.

忆沫 2024-12-06 20:18:11

如果你不能给它们提供它们应该处理的信息,函数将毫无用处。
参数就是这样的信息。

def GiveMeANumberAndIDuplicateIt(x):
    return x * 2

def DontGiveMeAnythingAtAll():
    return None

Functions would be useless if you can't give them information they should handle.
Arguments are such information.

def GiveMeANumberAndIDuplicateIt(x):
    return x * 2

def DontGiveMeAnythingAtAll():
    return None
半葬歌 2024-12-06 20:18:11

参数是仅存在于该函数中的特殊变量。

在您的示例中,您有一个带有 2 个参数的函数:

def add(num1,num2):
    x = num1 + num2
    return x

当我使用 add() 调用此函数时,我必须在括号中添加我想要的 num1num2 是。在您的例子中,您有 13,因此您可以这样调用它 add(1,3)

您的意思是,您想要调用 add() 并且希望第一个参数 num1 等于 1,第二个参数 num2 等于 3

An argument is a special variable that exists only in that function.

In your example you have a function that takes 2 arguments:

def add(num1,num2):
    x = num1 + num2
    return x

When I call this function with add(), I have to add in the parentheses what I want num1 and num2 to be. In your case, you have 1 and 3, so you call it like this add(1,3).

What you're saying there is that you want to call add() and you want the first argument, num1 to be equal to 1, and the second argument, num2, to be equal to 3.

一萌ing 2024-12-06 20:18:11
def main(a, b):
    print(a)
    print(b)

main(3, 5)

这是带有参数的函数的基本示例,请在此处查看更多信息< /a>.

输出:

3
5
def main(a, b):
    print(a)
    print(b)

main(3, 5)

This is a basic example of a function with parameters, check for more information here.

output:

3
5
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文