Python内部更改函数输入名称

2024-04-24 14:52:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要创建一个函数,它可以:

  1. 检查输入参数并获取输入数及其值
  2. 在每个输入后加上'
  3. 使新的输入全球化
  4. 用旧值指定新输入

我试着用检查.getargspec()但似乎应该在函数外部调用它。有什么建议吗?在

以下是伪代码: 定义此函数:

def set_global(a1, a2, a3, .... an):
    #the number of arguments is not fixed and we need to detect that
    for old_input in total input:
         new_input_name=str(old_input.name)+'_in'
         global new_input_name 
         new_input_name = old_input.value

Tags: 函数代码nameinnewinput参数定义
2条回答

我真的认为您在寻找globals函数。在

a = 1
globals()['a'] = 2
print a  #2
globals()['a_in'] = 2
print a_in  #2

你可以把它放到一个函数中:

^{pr2}$

可以这样称呼:

a = 1
b = 2
do_something_with_globals(a=a,b=b)
print a_in
print b_in

但是,老实说,我真的不认为这是个好主意。。。在

def foo(*args, **kwargs):
    print "number of fixed args: %d" % len(args)
    print "number of keyword args: %d" % len(kwargs)
    print "keyword argument names: %s" % str(kwargs.keys())

我们可以使用globals()来执行您想要的操作:

^{pr2}$

因此,使用Python交互式解释器中的上述函数:

>>> set_globals(foo='x', bar='y')
>>> foo_in
'x'
>>> bar_in
'y'

相关问题 更多 >