首页 > 解决方案 > 有没有办法动态检索对象方法并在 python 中调用它们?

问题描述

我想创建一个函数,如:

def test(x, way='a'):
    'a' = capitalize()
    'b' = lower()
    return x.way()

如果我在哪里运行:

test('ASD', way='b')

输出应该是:

'asd'

标签: python

解决方案


你可以实现你想要的,是的:

>>> method_map = dict(a='capitalize', b='lower')
>>> 
>>> def pick_method(text, method='a'):
...   return getattr(text, method_map[method])()
... 
>>> pick_method('UPPER', 'b')
'upper'

推荐阅读