python中函数参数中的相等是什么意思? [英] What does an equality mean in function arguments in python?

查看:26
本文介绍了python中函数参数中的相等是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是此处的代码示例:

函数的参数赋值中的相等是什么意思?像这里的 N=20000 吗?那和简单的 N 作为参数有什么区别?导入随机,数学

def gibbs(N=20000,thin=500):x=0y=0样品 = []对于范围(N)中的我:对于范围内的 j(薄):x=random.gammavariate(3,1.0/(y*y+4))y=random.gauss(1.0/(x+1),1.0/math.sqrt(x+1))样本.追加((x,y))退回样品smp = 吉布斯()

解决方案

在函数定义中,它指定参数的默认值.例如:

<预><代码>>>>定义功能(N = 20000):...打印(N)>>>功能(10)10>>>功能(N=10)10>>>功能()20000

在第一次调用中,我们为带有位置参数 10N 参数指定了一个值.在第二次调用中,我们使用关键字参数 N=10N 参数指定一个值.在第三次调用中,我们根本没有指定值——因此它使用默认值 20000.

请注意,使用关键字参数调用函数的语法与定义具有默认值参数的函数的语法非常相似.这种平行不是偶然的,但重要的是不要被它弄糊涂.当你开始解包参数与可变参数参数等时,更容易混淆自己. 除了最简单的情况外,即使你得到了它,而且这一切都在直觉上是有道理的,但实际上仍然很难获得细节直接在你的脑海里.这篇博文 试图将所有解释合而为一地方.我不认为它做得很好,但它至少有指向文档中所有相关内容的有用链接......

This is an example of of code from here:

What does the equality mean in the argument assignment to function? like N=20000 here? What is the difference between that and simply N as argument? import random,math

def gibbs(N=20000,thin=500):
   x=0
   y=0
   samples = []
   for i in range(N):
       for j in range(thin):
           x=random.gammavariate(3,1.0/(y*y+4))
           y=random.gauss(1.0/(x+1),1.0/math.sqrt(x+1))
       samples.append((x,y))
   return samples

smp = gibbs()

解决方案

In a function definition, it specifies a default value for the parameter. For example:

>>> def func(N=20000):
...     print(N)
>>> func(10)
10
>>> func(N=10)
10
>>> func()
20000

In the first call, we're specifying a value for the N parameter with a positional argument, 10. In the second call, we're specifying a value for the N parameter with a keyword argument, N=10. In the third call, we aren't specifying a value at all—so it gets the default value, 20000.

Notice that the syntax for calling a function with a keyword argument looks very similar to the syntax for defining a function with a parameter with a default value. This parallel isn't accidental, but it's important not to get confused by it. And it's even easier to confuse yourself when you get to unpacking arguments vs. variable-argument parameters, etc. In all but the simplest cases, even once you get it, and it all makes sense intuitively, it's still hard to actually get the details straight in your head. This blog post attempts to get all of the explanation down in one place. I don't think it does a great job, but it does at least have useful links to everything relevant in the documentation…

这篇关于python中函数参数中的相等是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆