小编md2*_*rpe的帖子

使类可以转换为元组和字典

我想定义一个类,以便它的实例可以转换为tupledict.一个例子:

class Point3:
    ...

p = Point(12, 34, 56)

tuple(p)  # gives (12, 34, 56)
dict(p)   # gives { 'x': 12, 'y': 34, 'z': 56 }
Run Code Online (Sandbox Code Playgroud)

我发现如果我定义__iter__为一个产生单个值的迭代器,那么实例可以被转换为tuple,如果它产生双值,那么它可以被转换为dict:

class Point3:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    # This way makes instance castable to tuple
    def __iter__(self):
        yield self.x
        yield self.y
        yield self.z

    # This way makes instance castable to dict
    def __iter__(self):
        yield …
Run Code Online (Sandbox Code Playgroud)

python dictionary iterable tuples python-2.7

7
推荐指数
2
解决办法
151
查看次数

标签 统计

dictionary ×1

iterable ×1

python ×1

python-2.7 ×1

tuples ×1