为什么给getitem分配一个类不起作用?

2024-03-28 21:34:09 发布

您现在位置:Python中文网/ 问答频道 /正文

这里有一个list子类,它将其项委托给^{}。你知道吗

from itertools import compress

class WeirdList(list):
    def __getitem__(self, item):
        return compress(self, item)

l = WeirdList([1, 2, 3, 4])
print(*l[0, 1, 0, 1]) # 2 4

上面的工作很好,尽管我觉得我可以直接将compress分配给__getitem__。你知道吗

class WeirdList(list):
    __getitem__ = compress

l = WeirdList([1, 2, 3, 4])
print(*l[0, 1, 0, 1])

这会引发以下问题:

Traceback (most recent call last):
  File "...", line 7, in <module> print(*l[0, 1, 0, 1])
TypeError: Required argument 'selectors' (pos 2) not found

我认为这是因为compress是一个类而不是一个函数,但是消息显示TypeError是从调用compress中产生的。你知道吗

在什么时候,__getitem__protcol用一个参数调用了compress?你知道吗


Tags: fromimportselfdefitem子类compresslist
1条回答
网友
1楼 · 发布于 2024-03-28 21:34:09

函数可以用作方法,因为它具有__get__属性。compress没有__get__属性:

>>> compress.__get__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module> 
AttributeError: type object 'itertools.compress' has no attribute '__get__'  

因此不能成为一种方法。你知道吗

使用__get__方法调用属性时,将调用__get__方法并返回其返回值,而不是属性本身的值。也就是说,l[0] == l.__getitem__(0) == l.__getitem__.__get__(l, type(l))(0),其中__get__的返回值是已经将l传递给函数的对象。你知道吗

(如果您曾经想知道classmethodstaticmethod修饰符是做什么的,它们用不同的__get__方法返回对象。)

相关问题 更多 >