Python 为什么';t将一个类分配给uu getitem_uu_u_u工作?
下面是一个Python 为什么';t将一个类分配给uu getitem_uu_u_u工作?,python,python-3.x,class,python-3.6,Python,Python 3.x,Class,Python 3.6,下面是一个列表子类,它将其项委托给 上面的工作很好,尽管我的印象是我可以直接将压缩分配给\uu getitem\uu 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> prin
列表
子类,它将其项委托给
上面的工作很好,尽管我的印象是我可以直接将压缩
分配给\uu getitem\uu
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
回溯(最近一次呼叫最后一次):
文件“…”,第7行,打印(*l[0,1,0,1])
TypeError:找不到必需的参数“选择器”(位置2)
我认为这是错误的,因为compress
是一个类而不是一个函数,但是消息显示TypeError
是调用compress
引起的
\uuu getitem\uuu
protcol在哪一点用单个参数调用了compress
?函数可以用作方法,因为它具有\uu get\uu
属性。类compress
没有\uu获取\uu
属性:
>>> compress.__get__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'itertools.compress' has no attribute '__get__'
>>压缩__
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
AttributeError:类型对象“itertools.compress”没有属性“\uuuu get\uuuu”
因此不可能是一种方法
使用\uuuuu get\uuuu
方法调用属性时,将调用\uuuu get\uuuu
方法并返回其返回值,而不是属性本身的值。也就是说,l[0]==l.\uuuu getitem\uuuuuuuu0==l.\uu getitem\uuuuuuuuuu.\uuuu get\uuuuuu(l,type(l))(0)
,其中\uu get\uuuuuuuu
的返回值是已经传递给函数的对象
(如果您曾经想知道
classmethod
和staticmethod
修饰符做什么,它们返回的对象具有不同的\uuuu get\uuuu
方法。)隐式添加self
作为第一个参数仅在从类检索函数时发生。您使用的Python版本是什么,这不是常见的Python3TypeError:toto()缺少1个必需的位置参数:“thing”
也不是Python2TypeError:toto()只接受2个参数(给定1个)
@BenoîtPilatte这是3.6.2版本Windows@jasonharper哦,完全有道理。这回答了我的问题。请随意写下答案。@jasonharper不一定是一个函数,而是一个具有适当的\uuu get\uuu
方法的东西(函数具有该方法)。定义\uu get\uu
方法的类称为描述符。详细描述其工作原理,请参见。还讨论了描述符协议是如何工作的。
>>> compress.__get__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'itertools.compress' has no attribute '__get__'