python - 有一个函数名(字符串形式),如何能够调用这个函数?
大家讲道理
大家讲道理 2017-04-18 10:22:29
0
2
601

比如:

def afunc():
    return 0

现在我有变量s='afunc',(此处仅举例,实际操作时名字是可变的)那么想调用afunc函数应当怎么操作呢?

补充说明:我的意思是,在实际应用中,我没有办法知道这个函数具体名字叫什么(上面的afunc只是随便举个例子),但我知道他的名字保存在一个字符串s中,我有的仅仅是s这个变量,那么我能不能通过这个s,来对那个函数进行调用

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
刘奇

According to your description, you can refer to the following code

Environment: python2.7.11

import sys
def afunc():
    return 0
s= "afunc"
get_afunc = getattr(sys.modules[__name__], s)
print get_afunc()

Run results

迷茫

Suppose the file you write this function in is called a.py, create a new file called b.py in the folder where a.py belongs, and write from a import afunc at the beginning of b.py, so that you are in b.py You can use afunc().

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!