python 3.x - Unpack class variables -
with collections.namedtuple 1 can make point = namedtuple('point', 'x y')
, set p = point(2,3)
, , unpack p
using x, y = p
.
can similar done 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 result in error of course, how can 1 effect of namedtuple?
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
Comments
Post a Comment