0

We could easily de-structure and assign variables using Python's builtin classes like list or tuples as seen below.

a, b = 1, 2

However, in cases where we do not wish to inherit those classes, and want our container to have a similar behaviour as seen in the snippet below, how would we do so? Is there a magic method?

class MyClass:
    ...

instance = MyClass()

# assuming there are some properties in the class for this
a, b = instance

An example that comes to mind would be dataclasses (although we could already do it with NamedTuple)

from dataclasses import dataclass

@dataclass
class MyClass:
    name: str
    age: int

instance = MyClass("John", 10)
name, age = instance
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
dbokers
  • 840
  • 1
  • 10
  • 12
  • You just need to make your instances *iterable* - so `__iter__()` is the method to implement. You can borrow the iterator implementation of some other container, so `return iter([self.name, self.age])` would be a working example. – jasonharper Aug 01 '20 at 03:01
  • Check this post: https://stackoverflow.com/questions/37639363/how-to-convert-an-custom-class-object-to-a-tuple-in-python – Mike67 Aug 01 '20 at 03:02
  • @jasonharper, you're right - it can be done via the __iter__ method. – dbokers Aug 01 '20 at 04:18

0 Answers0