Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中,使用函数时不要写出名称,而是在变量中使用info_Python - Fatal编程技术网

在python中,使用函数时不要写出名称,而是在变量中使用info

在python中,使用函数时不要写出名称,而是在变量中使用info,python,Python,我很抱歉,如果这已经出现,但无法在其他问题中找到解决方案。我想这样做: var1 = 'print' coolfunction(var1, 'aaa') # I want this to be the same as print('aaa') 因此,目标是使用存储在变量中的信息,并使用它指定要使用的函数 有什么方法可以在Python中执行类似的操作吗 我试过了 globals()['print']('will this work?') 但这不起作用。print是一个内置函数。所以你可以做如下

我很抱歉,如果这已经出现,但无法在其他问题中找到解决方案。我想这样做:

var1 = 'print'
coolfunction(var1, 'aaa') # I want this to be the same as print('aaa')
因此,目标是使用存储在变量中的信息,并使用它指定要使用的函数

有什么方法可以在Python中执行类似的操作吗

我试过了

globals()['print']('will this work?')

但这不起作用。

print
是一个内置函数。所以你可以做如下的事情

>>> import builtins
>>> getattr(builtins, 'print')('will this work?')
will this work?
对于自定义函数,使用
globals
的方法是可行的

>>> def myprint(*args, **kwargs):
...     print(*args, **kwargs)
... 
>>> globals()['myprint']('will this work?')
will this work?

也就是说,这样做是个坏主意,因为它会导致安全问题

打印是一个内置功能。所以你可以做如下的事情

>>> import builtins
>>> getattr(builtins, 'print')('will this work?')
will this work?
对于自定义函数,使用
globals
的方法是可行的

>>> def myprint(*args, **kwargs):
...     print(*args, **kwargs)
... 
>>> globals()['myprint']('will this work?')
will this work?

也就是说,这样做是个坏主意,因为它会导致安全问题

为什么需要传递函数名?为什么不传递函数本身呢
var1=print
…这取决于您使用它的方式,这是不安全的,但您可以使用
exec
。lambda表达式可能会有帮助[link]()感谢您提供的众多解决方案!为什么需要传递函数名?为什么不传递函数本身呢
var1=print
…这取决于您使用它的方式,这是不安全的,但您可以使用
exec
。lambda表达式可能会有帮助[link]()感谢您提供的众多解决方案!谢谢,这真的帮了我的忙!谢谢,这真的帮了我的忙!