search

Home  >  Q&A  >  body text

python - 有一个函数名(字符串形式),如何能够调用这个函数?

比如:

def afunc():
    return 0

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

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

大家讲道理大家讲道理2777 days ago631

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-18 10:24:29

    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

    reply
    0
  • 迷茫

    迷茫2017-04-18 10:24:29

    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().

    reply
    0
  • Cancelreply