【问题标题】:Custom object with __iter__() not returning what is defined in __tuple__()? [duplicate]带有 __iter__() 的自定义对象不返回 __tuple__() 中定义的内容? [复制]
【发布时间】:2017-10-19 19:27:09
【问题描述】:

在定义了__iter__()的自定义对象中,调用tuple(obj)时,它以元组形式返回__iter__()的数据,但我希望它从__tuple__()返回。

这是一个非常大的类,我不想在这里粘贴它。我写了一个较小的例子来说明我的问题。

class Example:
    def __init__(self, a, b):
        self.data = [a, b]

    def __iter__(self):
        return iter(reversed(self.data))

    def __tuple__(self):
        return map(str, self.data)


ex = Example(2, 3)

print([x for x in ex])  # Should return the data from __iter__().
>>> [3, 2]  # Reversed, good...

print(tuple(ex))  # Now calling: __tuple__().
>>> (3, 2)  # Should have returned ["2", "3"].

如果您需要查看我的所有代码,请询问,我会将其放入 Pastebin。我只是想为您省去整理所有这些额外方法的工作。

__iter__() 是否覆盖 __tuple__() 类型?出于某种原因,我无法将其更改为从 __tuple__() 返回应有的内容。

提前致谢。

【问题讨论】:

  • 您究竟是从哪里得到实现__tuple__ 方法的想法的?它不在data model 中。这是您应该预料到的行为。
  • 不可能print(tuple(ex)) 打印[3, 2]。那不是元组。
  • 请投票关闭它,因为如果它留下来会破坏我的代表。我曾假设__tuple__() 存在,老实说从未想过它不会。毕竟,__str__() 存在。
  • 关闭了。

标签: python python-3.x object methods


【解决方案1】:

__tuple__ 不是一个东西。 tuple 不寻找 __tuple__ 方法来执行转换为元组。我不知道你从哪里想到的。

【讨论】:

  • 因为__str__()存在。
  • @spikespaz,一个可以理解的推理链。 “__str____int__ 存在,所以也许每种内置类型都有一些笨拙的方法”,有人可能会想。但事实证明并非如此。
  • @Kevin 新词汇:dunder 方法。从未知道。朋友一直把它们称为“魔法”声明。
  • @spikespaz:请注意,dunders 只是一个命名约定;魔术方法的任何“魔术”都与下划线无关。例如,next 是在 Python 2 上从迭代器中检索项目的神奇方法。
猜你喜欢
  • 1970-01-01
  • 2018-09-15
  • 2013-01-22
  • 1970-01-01
  • 1970-01-01
  • 2012-10-10
  • 2018-02-20
  • 2020-04-08
  • 1970-01-01
相关资源
最近更新 更多