Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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

like image 863
PCM Avatar asked Oct 27 '25 01:10

PCM


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']
like image 93
Andrej Kesely Avatar answered Oct 29 '25 16:10

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!