Ask Your Question
0

make class iterable

asked 2012-10-03 03:14:12 +0100

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
4

answered 2012-10-03 05:55:59 +0100

Volker Braun gravatar image

Your class must implement an __iter__ method:

class Foo(SageObject):

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

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
0

answered 2012-10-03 03:40:50 +0100

SLOtoSF gravatar image

updated 2012-10-03 20:38:36 +0100

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

Stats

Asked: 2012-10-03 03:14:12 +0100

Seen: 787 times

Last updated: Oct 03 '12