【发布时间】:2017-07-11 00:10:54
【问题描述】:
我可以使用__iter__ 来定义自定义对象看起来像dict。有没有办法单独自定义tuple转换? (是的,我确实意识到这可能会令人困惑,并且可能很少几乎从来都不是一个好主意。)
默认行为:
>>>o = MyClass()
>>>dict(o)
{'value': 1, 'attr_1': "foo", 'attr_2': "bar"}
>>>tuple(o)
(('value', 1), ('attr_1', "foo"), ('attr_2', "bar"))
期望的行为:
>>>o = MyClass()
>>>dict(o)
{'value': 1, 'attr_1': "foo", 'attr_2': "bar"}
>>>tuple(o)
(1, {'attr_1': "foo", 'attr_2': "bar"})
这是o 所属类的一个最小示例:
class MyClass(object):
def __init__(self):
self.value = 1
self.attributes = {'attr_1': "foo", 'attr_2': "bar"}
def __iter__(self):
yield ("value", self.value)
for k, v in self.attributes.items():
yield (k, v)
相关,但不是关于 dict 和 tuple 的不同结构:special method for an object to override tuple expansion?
【问题讨论】:
-
我怀疑你能做到这一点。为什么不定义一个方法
o.to_tuple()? -
o的类型是什么? -
@MosesKoledoye 是的,这实际上就是我正在做的事情,但我很好奇我是否也可以让
tuple(o)表现相同,作为一种语法糖 -
@stamaimer 它属于一个自定义类(新式),如果这很重要?
-
可以显示自定义
__iter__的代码吗?
标签: python