You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过字典查找调用对象的成员函数?

列表成员方法的字典映射实现

直接用getattr()函数就能搞定——它可以获取列表对象的成员方法,把这些方法和对应名称存入字典后,就能通过字典键调用方法,效果和直接调用列表的成员方法完全一致。

基础实现示例

# 初始化目标列表
L = []
# 构建方法映射字典,把需要的列表方法绑定进去
method_dict = {
    'append': getattr(L, 'append'),
    'pop': getattr(L, 'pop'),
    'extend': getattr(L, 'extend'),
    'insert': getattr(L, 'insert')
}

# 调用测试
method_dict['append']("foo")  # 等价于 L.append("foo")
print(L)  # 输出: ['foo']

method_dict['pop']()  # 等价于 L.pop()
print(L)  # 输出: []

method_dict['extend'](["bar", "baz"])  # 等价于 L.extend(["bar", "baz"])
print(L)  # 输出: ['bar', 'baz']

适配HackerRank输入场景的用法

如果要处理从input()读取指令的情况(比如输入"append hello"这类指令),可以这样写:

L = []
method_map = {
    'append': getattr(L, 'append'),
    'pop': getattr(L, 'pop'),
    'remove': getattr(L, 'remove'),
    'sort': getattr(L, 'sort')
}

# 循环读取输入指令
n = int(input())
for _ in range(n):
    cmd = input().split()
    method_name = cmd[0]
    # 拆分出方法需要的参数
    args = cmd[1:]
    # 针对需要整数参数的方法做类型转换
    if method_name == 'pop' and args:
        args = [int(args[0])]
    # 调用对应方法
    if method_name in method_map:
        method_map[method_name](*args)

print(L)

比如输入:

5
append 1
append 2
sort
pop 1
append 3

最终列表会是[1, 3],和直接调用列表方法的结果完全一致。

原理很简单:getattr(L, 'append')返回的是绑定到L的append方法,调用这个方法时,会自动把L作为第一个参数(也就是self)传入,所以直接传方法需要的参数就行,不用再指定对象。

内容的提问来源于stack exchange,提问作者gglazer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 15:16:03