有没有一种方法可以动态检索对象方法并在python中调用它们?

时间:2020-01-31 22:07:15

标签: python

我想创建一个像这样的函数:

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

如果我在哪里跑步,

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

输出应为:

'asd'

2 个答案:

答案 0 :(得分:1)

您可以实现自己想要的,是的:

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

答案 1 :(得分:0)

以下内容如何?

width

编辑:

在帖子评论的后面添加文字,您还可以传入一个函数作为参数(尽管此时,您真的可以直接调用func(x)):

height