[英]Python: define arguments of a function which include the arguments of the other function
Please let me know if there are duplicated ones (I believe there are) and I will remove the post. 请让我知道是否有重复的邮件(我相信有),我将删除该帖子。 I am just not sure about the jargon for this question. 我只是不确定这个问题的行话。
When writing a new function augmented_func
which contains the other function already defined original_func
, I am trying to avoid defining arguments that are already in original_func
: 在编写包含另一个已经定义的其他函数original_func
的新函数augmented_func
的功能时,我试图避免定义已经在original_func
参数:
def original_func(a1, a2 ,a3):
print(a1, a2, a3)
def augmented_func(b, a1, a2, a3):
print(original_func(a1, a2, a3), b)
How do I avoid writing a
's when defining augmented_func
, and make it simpler especially when the number of arguments for original_func
is more than, say, three in the example? 如何避免写a
定义时的augmented_func
,并简化尤其是当论据数量original_func
超过,比如说,三中的例子吗?
Use *
notation for an arbitrary number of positional arguments: 对任意数量的位置参数使用*
表示法:
def augmented_func(b, *args):
print(original_func(*args), b)
augmented_func('b', 1, 2, 3)
Or use keyword arguments with **
: 或使用带有**
关键字参数:
def augmented_func(b, **kwargs):
print(original_func(**kwargs), b)
augmented_func('b', a1=1, a2=2, a3=3)
I think what you looking for is something like 我想你在找什么
def original_func(a1, a2 ,a3):
print(a1, a2, a3)
def augmented_func(b, *args):
print(original_func(*args), b)
you can call it then as augmented_func(1, 2, 3, 4)
您可以称其为augmented_func(1, 2, 3, 4)
*args
and **kwargs
is a good way for passing the variable number of arguments and passing them to other internal function calls. *args
和**kwargs
是传递可变数量的参数并将其传递给其他内部函数调用的好方法。
Python docs for further info. Python文档以获取更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.