Ask Your Question

make class iterable

asked 2012-10-02 20:14:12 -0500

SLOtoSF gravatar image

How do I make a class iterable?

I want to create a class, which is a set of objects that I created, that has attributes of its own.

The user experience I am thinking of is the following:

(let's say A, B, and C are Objects in memory)

sage: D = Box((A,B,C))

I want to be able to say for i in D: ....

But I can't.

Any tips?

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted

answered 2012-10-02 22:55:59 -0500

Volker Braun gravatar image

Your class must implement an __iter__ method:

class Foo(SageObject):

    def __iter__(self):
        for i in range(10):

Then you can just say:

sage: bar = Foo()
sage: list(bar)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
edit flag offensive delete link more

answered 2012-10-02 20:40:50 -0500

SLOtoSF gravatar image

updated 2012-10-03 13:38:36 -0500

The answer to this question is the derive the class from a set, but I think Volker's answer is to the point.

Like so:

class MyClass(set):

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2012-10-02 20:14:12 -0500

Seen: 75 times

Last updated: Oct 03 '12