__iter__
を使用して、カスタムオブジェクトの表示方法をdict
として定義できます。 tuple
のコンバージョンを個別にカスタマイズする方法はありますか? (はい、私はこれが潜在的に混乱していることを認識し、そしておそらくまれほとんどない良いアイデアです。)オブジェクトの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)
に属しています。
関連ではなく、辞書やタプルのための異なる構造体を持っていることについて:special method for an object to override tuple expansion?
私はこれを行うことはできません。 'o.to_tuple()'メソッドを定義してみませんか? –
'o'の種類は何ですか? – stamaimer
@MosesKoledoye確かに私がやっていることですが、 'tuple(o)'も同じように振る舞うことができるのか不思議でした。 – leo