如何更改 Python 中 index() 方法的名称?

How can I change the name of the index() method in Python?

我说的方法

list.index()

这是我的代码

pt(dt, 'ml', proof.index(ds['pf']), p.index(dt['ps']), d.index(da['dp']), m.index(db['mc']))

而且我想这样写,把"index"换成"ix"

pt(dt, 'ml', proof.ix(ds['pf']), p.ix(dt['ps']), d.ix(da['dp']), m.ix(db['mc']))

我试过

import index as ix

它没有用(虽然很明显)。甚至可以这样做吗?有没有办法访问此方法并将其导入为 x、a、b 等?

可以改吗?

这对于内置插件是不可能的(用户定义的 类 可以被猴子修补,内置插件不能,至少不能以任何不涉及可怕黑客的合理方式C层);您可以子类化 list,将 ix 定义为 list.index 的别名,并将子类用于所有类型而不是普通的 list,但这很丑陋且不值得。

无需更改整个代码库即可使用 list 子类的最接近方法是创建名称较短的 attrgetter 并使用它:

from operator import attrgetter

ix = attrgetter('index')  # Done once at global scope early in file and reused later

pt(dt, 'ml', ix(proof)(ds['pf']), ix(p)(dt['ps']), ix(d)(da['dp']), ix(m)(db['mc']))

但坦率地说,这也不是特别好看(并且在运行时启动速度会更慢,因为它禁用了方法调用优化);只需拼出 index 并使您的代码可读。