0

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?

wjandrea
  • 28,235
  • 9
  • 60
  • 81

2 Answers2

3

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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
rdas
  • 20,604
  • 6
  • 33
  • 46
  • What about a meta-scope where I can do this ? myClass_atrributename = myClass(a, b). So if your class has an attribute named “myClass_attributename” to return that value –  Mar 11 '20 at 21:05
  • 2
    I'm not sure if I understood that – rdas Mar 11 '20 at 21:06
  • 1
    I think @entropyfeverone might be trying to refer to `getattr`? Like `getattr(myclass(a, b), 'myClass_attributename')` – Tomerikoo Mar 11 '20 at 21:45
1

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81