Skip to main content
 首页 » 编程设计

python之在 python 中,有什么方法可以获取作为对象传递给函数的参数

2025年05月04日14lyj

我不想使用 *args 或 **kwargs,因为我无法更改函数声明。

例如:

def foo( a, b, c ) """Lets say values passed to a, b and c are 1,2 and 3 respectively""" 
   ... 
   ... 
   """ I would like to generate an object preferably a dictionary such as {'a':1, 'b':2, 'c':3} """ 
   ... 
   ... 

谁能推荐一种方法来做到这一点? 提前致谢。

请您参考如下方法:

如果你不能改变函数“声明”(为什么不呢?)但是你可以改变函数的内容,那么只要创建你想要的字典就可以了:

def foo(a, b, c): 
    mydict = {'a': a, 'b': b, 'c': c} 

如果这不起作用,我认为您需要更好地解释您想要什么以及您的情况有哪些限制。

这也会在上述情况下给出类似的结果(您不显示参数以外的任何局部变量),但要注意 you should not try to modify locals() :

def foo(a, b, c): 
    mydict = locals()