分配(而不是定义)一个 __getitem__ 魔术方法会破坏索引 [英] Assigning (instead of defining) a __getitem__ magic method breaks indexing

查看:25
本文介绍了分配(而不是定义)一个 __getitem__ 魔术方法会破坏索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于这个(高度简化的)例子的包装类:

I have a wrapper class similar to this (strongly simplified) example:

class wrap(object):
    def __init__(self):
        self._data = range(10)

    def __getitem__(self, key):
        return self._data.__getitem__(key)

我可以这样使用它:

w = wrap()
print w[2] # yields "2"

我想我可以通过改成这样来优化和摆脱一个函数调用:

I thought I could optimize and get rid of one function call by changing to this:

class wrap(object):
    def __init__(self):
        self._data = range(10)
        self.__getitem__ = self._data.__getitem__

但是,我收到了一个

TypeError: 'wrap' 对象不支持索引

TypeError: 'wrap' object does not support indexing

对于后面版本的 print w[2] 行.

for the print w[2] line with the latter version.

直接调用该方法,即print w.__getitem__(2),在两种情况下都适用...

The direct call to the method, i.e., print w.__getitem__(2), works in both cases...

为什么作业版本不允许索引?

Why does the assignment version not allow indexing?

推荐答案

必须在类中定义特殊方法(基本上是每端有两个下划线的任何方法).特殊方法的内部查找过程完全跳过了实例字典.除其他事项外,如果您这样做

Special methods (essentially anything with two underscores on each end) have to be defined on the class. The internal lookup procedure for special methods completely skips the instance dict. Among other things, this is so if you do

class Foo(object):
    def __repr__(self):
        return 'Foo()'

您定义的 __repr__ 方法仅用于 Foo 的实例,而不用于 repr(Foo).

the __repr__ method you defined is only used for instances of Foo, and not for repr(Foo).

这篇关于分配(而不是定义)一个 __getitem__ 魔术方法会破坏索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆