英文:
How to call a function with it's parameters stored in a variable python
问题
我有一个包含函数的变量,还有一个包含我想要作为元组传递给它的参数的变量。如何使用这些参数调用该函数?
示例
func = self.my_func
params = (1, 2, 3)
func(*params)
我想做类似上面的代码,但这不起作用,因为该语法只将元组作为单个参数传递。正确的语法是什么?
英文:
I have a variable that contains a function, and one that has the parameters I want to pass to it as a tuple. How can I call that function with those parameters?
# Example
func = self.my_func
params = (1, 2, 3)
func(params)
I want to do something like the code above, but it doesn't work since that syntax just takes the tuple as a single parameter. What is the right syntax to do this?
答案1
得分: 2
要将params元组的元素作为单独的参数传递给func函数,您可以使用解包运算符*。通过在params前添加*,元组params的元素将被解包,并作为单独的参数传递给func函数。这样,在调用func时,元组的每个元素都将被视为单独的参数。我认为这满足了您的要求。
这是修改后的代码:
func = self.my_func
params = (1, 2, 3)
func(*params)
英文:
To pass the elements of the params tuple as individual arguments to the func function, you can use the unpacking operator *. By adding * before params, the elements of the tuple params will be unpacked and passed as separate arguments to the func function. This way, each element of the tuple will be treated as an individual argument when calling func. I think it satisfies you.
Here's the modified code:
func = self.my_func
params = (1, 2, 3)
func(*params)
答案2
得分: 2
要从元组中调用带有参数的函数,您可以使用*
运算符来展开元组。以下是实现这一目标的正确语法:
func(*params)
在您的示例中,您可以使用以下代码调用函数my_func
并传递参数(1, 2, 3)
:
func = self.my_func
params = (1, 2, 3)
func(*params)
这将展开元组并将其元素作为单独的参数传递给函数。
英文:
To call a function with parameters from a tuple, you can use the *
operator to unpack the tuple. Here's the correct syntax to achieve this:
func(*params)
In your example, you can call the function my_func
with the parameters (1, 2, 3)
using the following code:
func = self.my_func
params = (1, 2, 3)
func(*params)
This will unpack the tuple and pass its elements as separate arguments to the function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论