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

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

问题描述

这是此处:

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

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

在第一个调用中,我们为 N 参数指定了一个带有位置参数 10 的值.在第二个调用中,我们为 N 参数指定一个带有关键字参数 N = 10 的值.在第三个调用中,我们根本没有指定任何值,因此它将获得默认值 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天全站免登陆