84669 person learning
152542 person learning
20005 person learning
5487 person learning
7821 person learning
359900 person learning
3350 person learning
180660 person learning
48569 person learning
18603 person learning
40936 person learning
1549 person learning
1183 person learning
32909 person learning
比如:
def afunc(): return 0
现在我有变量s='afunc',(此处仅举例,实际操作时名字是可变的)那么想调用afunc函数应当怎么操作呢?
s='afunc'
补充说明:我的意思是,在实际应用中,我没有办法知道这个函数具体名字叫什么(上面的afunc只是随便举个例子),但我知道他的名字保存在一个字符串s中,我有的仅仅是s这个变量,那么我能不能通过这个s,来对那个函数进行调用
光阴似箭催人老,日月如移越少年。
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().
According to your description, you can refer to the following code
Environment: python2.7.11
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().