相关疑难解决方法(0)

参数解包是使用迭代还是项目获取?

我正在使用Python 2.7.3.

考虑一个带有自定义(虽然很糟糕)迭代和项目获取行为的虚拟类:

class FooList(list):
    def __iter__(self):
        return iter(self)
    def next(self):
        return 3
    def __getitem__(self, idx):
        return 3
Run Code Online (Sandbox Code Playgroud)

举个例子,看看奇怪的行为:

>>> zz = FooList([1,2,3])

>>> [x for x in zz]
# Hangs because of the self-reference in `__iter__`.

>>> zz[0]
3

>>> zz[1]
3
Run Code Online (Sandbox Code Playgroud)

但现在,让我们创建一个函数,然后执行参数解包zz:

def add3(a, b, c):
    return a + b + c

>>> add3(*zz)
6
# I expected either 9 or for the interpreter to hang like the comprehension!
Run Code Online (Sandbox Code Playgroud)

因此,参数解包以某种方式获取项数据,zz但不是通过使用其实现的迭代器迭代对象,也不是通过执行穷人的迭代器并调用__getitem__与对象一样多的项.

所以问题是:如果不通过这些方法,语法如何add3(*zz) …

python iterator arguments

12
推荐指数
1
解决办法
1099
查看次数

什么是映射对象,根据dict类型?

文档列出了创建dict实例的3种方法:

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
Run Code Online (Sandbox Code Playgroud)

这里的映射究竟是什么?dict(mapping)工作所需的最小接口是什么?

python mapping dictionary

12
推荐指数
3
解决办法
5254
查看次数

python中的重载*运算符(或模拟它)

我想在python中重载*运算符.在C++中,您可以重载取消引用运算符,以便您可以创建一个具有自定义响应方式的类*alpha.

这个问题的一部分是我完全不知道,我的意思是,*运算符(我称之为解包运算符)的确如此.

那么如何重载它,或模拟它的重载.

最终我希望能够:*alpha使用自定义响应和返回值.


编辑:

感谢Joe Kington的评论,我找到了解决方案.作为*alpha根据解压缩__iter__,所以我定义了一个可以继承的简单类来允许这个.

顺便说一句,我希望能够做到这一点的原因是因为我想要一个漂亮的界面.

class Deref:
  def __deref__(self):
    pass

  def __iter__(self):
    yield self.__deref__()

class DerefTest(Deref):
  def __deref__(self):
    return '123cat'

if __name__ == '__main__':
  print(*DerefTest()) # prints '123cat'
Run Code Online (Sandbox Code Playgroud)

最后我只是决定使用另一个一元运算符,因为我给出的实现在所有情况下都不起作用,所以我很失望.

python overloading unpack operator-keyword

3
推荐指数
1
解决办法
1701
查看次数

将元组的迭代转换为每个元素的迭代(Python)

我有一个迭代delta生成两个数字的元组(dx, dy),我想计算每个数的总和.以下不起作用,因为delta在第一次迭代后处理.

x = sum(dx for dx, dy in delta)
y = sum(dy for dx, dy in delta)
Run Code Online (Sandbox Code Playgroud)

任何的想法?我想在莫名其妙地转动方向delta为两个iterables dxdy,但到目前为止已经达到什么.

python iterable generator-expression python-3.x

3
推荐指数
1
解决办法
238
查看次数