Is there a magic and dunder method to make a list object in python OOP

Viewed 218

For example - I have a class

class SimpleClass:
      def __init__(self,strings):
          pass

Can i add a special method to this like __list__ or something, so that when i do this -

a = SimpleClass('hi')
list(a)

will make a list of the string but with more of my own methods. I mean that when i call list(a) a list will be created of the string plus with some of my extra strings to that list

1 Answers

You can implement __iter__ method. For example:

class SimpleClass:
    def __init__(self, strings):
        self.strings = strings

    def __iter__(self):
        yield self.strings
        yield "something else"


a = SimpleClass("hi")
print(list(a))

Prints:

['hi', 'something else']
Related