python - 在 Python 中传递多个不同的函数参数
问题描述
首先,我已经看到了许多类似的问题,尽管它们并不完全是我的问题。我已经很熟悉了*args 和 **kwargs。
问题解释:
我通常在调用函数时使用位置参数。但是,我经常发现自己需要将过多的参数传递给函数,因此使用位置参数变得相当繁琐。我还发现自己需要将不同数量的变量传递给一个可以在需要时接受更多或其他变量的函数。
如何将许多参数传递给能够接受不同数量参数的函数?
我试图创建一个尽可能基本的示例。这些函数只是对一些变量执行一些算术运算,然后将它们打印出来。
a = 10
b = 20
c = 30
def firstFunction(*args):
d = a *2
e = b /2
f = c +2
x = d -10
y = e -10
z = f -10
h = 1 #or 2
secondFunction(d,e,f,h)
thirdFunction(x,y,z,h)
def secondFunction(d,e,f,h):
if h == 1:
print d
print e
print f
def thirdFunction(x,y,z,h):
if h == 2:
print x
print y
print z
firstFunction(b,c,a)
正如预期的那样,对于 h=1 和 h=2 分别产生的结果是:
20
10
32
10
0
22
现在假设我想将第二个和第三个函数组合在一起,所以我只需要调用一个函数而不是两个。在这种情况下,函数将是:
def combinedFunction(d,e,f,h,x,y,z):
if h == 1:
print d
print e
print f
if h == 2:
print x
print y
print z
并会被调用:combinedFunction(d,e,f,h,x,y,z)
。可以想象,对于更复杂的功能,这可能会变得非常烦人。此外,我传递了许多根本不会使用的不同参数,并且必须首先声明它们中的每一个。例如,在示例中, if h = 1
, x
, y
andz
仍然必须传递给函数,并且其中一个的值可能尚未确定(在这个简单的情况下是这样)。我不能使用 'combinedFunction(*args)' 因为不是每个参数都是全局定义的。
TLDR:
基本上我想要以下内容:
def someFunction(accepts any number of arguments **and** in any order):
# does some stuff using those arguments it received at the time it was called
# it can accept many more parameters if needed
# it won't need to do stuff to a variable that hasn't been passed through
这个函数被调用:
someFunction(sends any number of arguments **and** in any order)
# can call the function again using different arguments and a
# different number of arguments if needed
这很容易实现吗?
解决方案
在函数内部使用全局变量通常是一种不好的方法。取而代之的是,您可以使用**kwargs
这种方式:
def firstFunction(**kwargs):
d = kwargs.get('a') * 2
secondFunction(d=d, **kwargs)
thirdFunction(e=1, **kwargs)
def secondFunction(d, **kwargs):
print d
print kwargs.get('a')
def thirdFunction(**kwargs):
print kwargs.get('e')
firstFunction(a=1, b=3, q=42) # q will not be used
推荐阅读
- azure - 由于 X-ORIGINAL-URL 标头(CVE-2018-14773),Cloudflare 阻止了我们的“子域之间”url 重写为 403
- mongodb - 如何使用代码将 MongoDB 中的数据类型更改为 pymongo (Python)
- android - 从 Cloud Firestore 中获取数据
- angular - 如果在表单中,角度 ng-autocomplete 不会设置初始值
- java - Java 开放地理工具
- google-apps-script - 如何避免根据同一日期范围内的列值插入一行数据?
- shell - Linux从文本行内部剪切字段
- typescript - 如何使用仅适用于特定 IP 地址的 AWS CDK 部署 S3 存储桶(NotIpAddress 条件)?
- laravel - 刷新页面时保持在数据表中输入的搜索值vue.js
- css - 子选择器和相邻兄弟选择器有什么区别?