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

115 Views Asked by At

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?

2

There are 2 best solutions below

3
rdas On BEST ANSWER

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
0
wjandrea On

If your class doesn't do much else, you might prefer to use a named tuple:

from collections import namedtuple

MyClass = namedtuple('MyClass', 'a b')
mc = MyClass(1, 2)
print(mc.a, mc.b)  # -> 1 2
x, y = mc
print(x, y)  # -> 1 2

BTW, style note: Class names should be UpperCamelCase.