pythonpython-3.xiterable-unpackingmagic-function

How to a, b = myClass(a, b) in Python?


Python does this:

t = (1, 2)
x, y = t
# x = 1
# y = 2

How can I implement my class so to do

class myClass():
    def __init__(self, a, b):
        self.a = a
        self.b = b

mc = myClass(1, 2)
x, y = mc
# x = 1
# y = 2

Is there a magic function I could implement in order to achieve this?


Solution

  • You need to make your class iterable. Do this by adding the __iter__ method to it.

    class myClass():
        def __init__(self, a, b):
            self.a = a
            self.b = b
    
        def __iter__(self):
            return iter([self.a, self.b])
    
    mc = myClass(1, 2)
    
    x, y = mc
    
    print(x, y)
    

    Output:

    1 2