python怎么实现按照文本顺序执行函数

如题所述

Python读文本可以用with上下文管理器。根据文本来执行对应名字的函数可以用getatter方法。代码如下:
首先,新建文本文件test.txt,内容如下:
func1,life is short
func2,use python
func1, hello word

下面是Python代码,声明两个function,功能是打印出传入的参数。main里面的把内容就是按照文本的顺序,传入参数执行对应的function:
class Example(object):

def __init__(self):
pass

def func1(self, arg):
print 'this is func1, arg is {}.'.format(arg)

def func2(self, arg):
print 'this is func2, arg is {}.'.format(arg)if __name__ == '__main__':
example_instance = Example()

with open('test.txt', 'r') as f:
for line in f.readlines():
function_name, args = line.strip().split(',')
getattr(example_instance, function_name)(args)

得到这样的输出:
this is func1, arg is life is short.
this is func2, arg is use python.
this is func1, arg is hello word.
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答