1

With collections.namedtuple one can make a Point = namedtuple('Point', 'x y') and set p = Point(2,3), and unpack p using x, y = p.

Can something similar be done with classes? e.g

class Point:
    def __init__(self,x ,y):
        self.x = x
        self.y = y
p = Point(2,3)
x,y = p
print(f"x: {x}, y: {y}")
>>> x: 2, y: 3

This would result in an error of course, but how can one get the effect of the namedtuple?

Frank Vel
  • 1,202
  • 1
  • 13
  • 27
  • 2
    tl;dr: Implement `__iter__` – anthony sottile Sep 10 '17 at 21:04
  • 2
    You could but in most cases it would be an odd thing to do with a class. A tuple is immutable so the mapping between named key and index is also immutable. Classes generally don't offer the same guarantees. – pvg Sep 10 '17 at 21:07

2 Answers2

2
class Point:
    def __init__(self, x, y):
        self._flag = 2
        self.x = x
        self.y = y

    def __iter__(self):
        return self

    def __next__(self):
        if self._flag == 2:
            self._flag = 1
            return self.x
        elif self._flag == 1:
            self._flag = 0
            return self.y
        else:
            raise StopIteration()


p = Point(5, 6)

(x, y) = p
-1

To get the effect of named tuple make your class a subclass of tuple. See my similar question and answer

DaftVader
  • 105
  • 1
  • 11