Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make class castable to both tuple and dict

Tags:

I would like to define a class so that its instances can be casted to both tuple and dict. An example:

class Point3:
    ...

p = Point(12, 34, 56)

tuple(p)  # gives (12, 34, 56)
dict(p)   # gives { 'x': 12, 'y': 34, 'z': 56 }

I have found that if I define __iter__ as an iterator that yields single values then the instance can be casted to tuple and if it instead yields double values then it can be casted to 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 'x', self.x
        yield 'y', self.y
        yield 'z', self.z

Is there any way to make instances castable to both tuple and dict in Python 2.7?