Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么';t将一个类分配给uu getitem_uu_u_u工作?_Python_Python 3.x_Class_Python 3.6 - Fatal编程技术网

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版本是什么,这不是常见的Python3
TypeError:toto()缺少1个必需的位置参数:“thing”
也不是Python2
TypeError: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__'