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

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

问题描述

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

  b def __init __(self):
self._data = range(10)

def __getitem __(self,key):
return self._data .__ getitem __(key)

我可以这样使用:

  w = wrap()
print w [2]#产生2


b $ b

我认为我可以优化和摆脱一个函数调用,改为:

 对象):
def __init __(self):
self._data = range(10)
self .__ getitem__ = self._data .__ getitem__

但是,我收到了一个


TypeError:'wrap'不支持索引


print w [2]



直接调用该方法,即 print w .__ getitem __(2)两种情况...



为什么分配版本不允许索引?

解决方案

必须在类上定义特殊方法(基本上任何两端都有两个下划线)。特殊方法的内部查找过程完全跳过实例dict。其他事情,这是如此如果你做

  class Foo(object):
def __repr __
return'Foo()'

__ repr __ 方法仅用于 Foo 的实例,而不是 repr(Foo)的实例。 / p>

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)

I can use it like this:

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__

However, I receive a

TypeError: 'wrap' object does not support indexing

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

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()'

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

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

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