实现说明
各个操作都建立在顶层绑定之上:services、by_status、names、flagged。
使用要点
- 直接运行文件,输出会带上标签,比如
sorted by status:、case-insensitive:——输出的每一行都能指回产生它的那次调用。
常见问题
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 全部导入都来自标准库:operator。 跨调用保留的状态放在这些顶层绑定里:services、by_status、names。
代码示例
from operator import methodcaller
# methodcaller(方法名, *参数) 生成"对每个对象调用该方法"的可复用键函数
services = [
{"name": "billing", "status": "degraded"},
{"name": "auth", "status": "ok"},
{"name": "search", "status": "ok"},
]
# dict.get 也是方法:methodcaller('get', 'status') 等价于 lambda d: d.get('status')
by_status = sorted(services, key=methodcaller("get", "status"))
print("sorted by status:", [s["name"] for s in by_status])
# 带参数调用:methodcaller('startswith', 'py') 检查每个元素
names = ["python", "javascript", "pypy", "rust"]
flagged = [n for n in names if methodcaller("startswith", "py")(n)]
print("startswith py :", flagged)
# 与 itemgetter/attrgetter 同族:itemgetter 取字段,methodcaller 调方法
words = ["Banana", "apple", "Cherry"]
print("case-insensitive:", sorted(words, key=methodcaller("lower")))
# 链式参数:methodcaller('replace', ...) 一次替换所有元素里的内容
print("replaced :", [methodcaller("replace", "a", "@")(w) for w in words])