just for fun: make a class (not its instances) iterable

Chris Kaynor ckaynor at zindagigames.com
Tue Aug 9 23:51:31 CEST 2011


You can using metaclasses (untested):

>>>class MyMetaClass(type):
>>>    def __iter__(self):
>>>        return [1, 2, 3, 4]

>>>class MyClass(object):
>>>    __metaclass__ = MyMetaClass

>>>for value in MyClass:
>>>    print value
1
2
3
4

Chris


On Tue, Aug 9, 2011 at 2:43 PM, Gelonida N <gelonida at gmail.com> wrote:

> Hi,
>
> I am just curious. There  is no real use case:
>
> If I have a class and I want that its instances are iterable I can just
> add a class metohod named __iter__()
>
>
> example:
>
> class MyClass(object):
>        def __iter__(self):
>                for val in range(10):
>                        yield val
>
>
> this allows me to do:
> myobj = MyClass()
> for val in myobj:
>        print val
>
>
> Now I wondered whether there is any way to  implement a class such, that
> I can write
>
>
> for val in MyClass:
>        print val
>
> I know I can implement  a classmethod (e.g myclassmethod() ) and write:
>
> for val in MyClass.myclassmethod():
>        print val
>
> but I wondered whether classed can be made iterable
>
> Thanks in advance for your answers.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110809/41c7055d/attachment.html>


More information about the Python-list mailing list