python - 有没有办法动态检索对象方法并在 python 中调用它们?
问题描述
我想创建一个函数,如:
def test(x, way='a'):
'a' = capitalize()
'b' = lower()
return x.way()
如果我在哪里运行:
test('ASD', way='b')
输出应该是:
'asd'
解决方案
你可以实现你想要的,是的:
>>> method_map = dict(a='capitalize', b='lower')
>>>
>>> def pick_method(text, method='a'):
... return getattr(text, method_map[method])()
...
>>> pick_method('UPPER', 'b')
'upper'
推荐阅读
- jupyter-notebook - 如何在 Heatmap 上绘制饼图?
- python - 如何组合字符符号列表中的两个字符串
- arrays - C. 基础。退出循环
- anychart - 如何控制 AnyChart 的 Word Tree 中分支的截断?
- node.js - 如何在游戏更新推送到 Steam 时获得“通知”?
- python - 使用 python (Jupyter notebook) 对 json 数据进行数据预处理
- python - 如果未通过,Pytest 会跳过寻找间接参数吗?
- javascript - Javascript 在页面上给我一个 NaN 但在控制台中给我一个数字?
- c - 对链表节点数组进行排序
- kubernetes - haproxy 登录 kubernetes 容器