使用字符串调用函数

2024-05-17 15:31:40 发布

您现在位置:Python中文网/ 问答频道 /正文

from en import verb
print verb.tenses()
print verb.infinitive('argue')


['infinitive', 'present participle', 'past plural', '2nd singular present', '2nd singular past', 'past', '3rd singular present', 'past participle', '1st singular present', '1st singular past', '3rd singular past', 'present plural']
    argue

Using this。你知道吗

我找不到一个能给出动词所有时态的方法。调用每个函数只有一种方法:用动词宾语替换列表中的空格。我怎样才能做到这一点?你知道吗

输入:argue。输出应该是:arguingarguedargue。。你知道吗


Tags: 方法fromimport动词enpastprintverb
2条回答

您可以执行getattr(verb, 'infinitive'),它将返回与verb.infinitive完全相同的函数的引用。然后,您可以循环浏览如下字符串列表:

some_tenses = ['infinitive', 'present_participle', 'past_plural',]
for tense in some_tenses:
    print getattr(verb, tense)('argue')

当然,字符串必须是模块中确切的函数名,不管它们是什么。你知道吗

您可能还想查看hasattr()。如果您尝试getattr()但是您为该对象提供的属性不存在,您将得到AttributeError。在尝试if hasattr(...之前使用getattr(...可以让您优雅地处理此类情况。或者,您可以使用try…except block。你知道吗

您可以为时态的每个名称创建一个名称/参数列表。例如:

tense_functions = {
    'infinitive': ('infinitive', {}),
    'present participle': ('present_participle', {}),
    '1st singular present': ('present', {'person': 1}),
    ...
}
for tense in verb.tenses():
    options = tense_functions[tense]
    func = getattr(verb, options[0])
    print(func('argue', **options[1]))

相关问题 更多 >