python - special method for an object to override tuple expansion? -


i provide example of problem in question, in case title not clear enough.

let's have class point(object) represent 2d coordinates. possible create "magic" method allow following?

x, y = point 

maybe hacks iterators?

just provide __iter__ method.

class point(object):     def __init__(self, x, y):         self.x = x         self.y = y     def __iter__(self):         yield self.x         yield self.y  p = point(1, 2) x, y = p assert (1, 2) == (x, y) 

be careful though. means class becomes safe use in many other places might have thrown type error.

eg.

def add_1(x):     return x + 1 l = list(map(add_1, p)) # works, because point iterable 

ergo, may want provide method other __iter__ provides iterator.

eg.

class point(object):     def __init__(self, x, y):         self.x = x         self.y = y     def coords(self):         yield self.x         yield self.y  p = point(1, 2) x, y = p.coords() assert (1, 2) == (x, y) 

Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -