3

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

PCM
  • 2,881
  • 2
  • 8
  • 30

1 Answers1

5

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']
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 2
    @PCM You don't have to use `yield`, but it's easiest. For example, look here: https://stackoverflow.com/a/40255361/10035985 – Andrej Kesely Jun 26 '21 at 07:53
  • Similarly, what is the method for dict and set and tuple. – PCM Jun 26 '21 at 07:57
  • the same mechanism that works for `list` works for `tuple` and `set`: just like `l = list(a)` will return a `list`, so `s = set(a)` and `t=tuple(a)` will return a `set` and a `tuple` respectively. For `dict`, which result would you expect? Which keys, and which values? – gimix Jun 26 '21 at 11:08
  • Anyhow, `d = dict(zip(["key1","key2],a))` will return a `dict` – gimix Jun 26 '21 at 11:14