ASKSAGE: Sage Q&A Forum - Individual question feedhttp://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Tue, 02 Oct 2012 22:55:59 -0500make class iterablehttp://ask.sagemath.org/question/9381/make-class-iterable/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?
Tue, 02 Oct 2012 20:14:12 -0500http://ask.sagemath.org/question/9381/make-class-iterable/Answer by Volker Braun for <p>How do I make a class iterable? </p>
<p>I want to create a class, which is a set of objects that I created, that has attributes of its own.</p>
<p>The user experience I am thinking of is the following:</p>
<p>(let's say A, B, and C are Objects in memory)</p>
<p>sage: D = Box((A,B,C))</p>
<p>I want to be able to say <code>for i in D: ....</code></p>
<p>But I can't. </p>
<p>Any tips?</p>
http://ask.sagemath.org/question/9381/make-class-iterable/?answer=14101#post-id-14101Your 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]
Tue, 02 Oct 2012 22:55:59 -0500http://ask.sagemath.org/question/9381/make-class-iterable/?answer=14101#post-id-14101Answer by SLOtoSF for <p>How do I make a class iterable? </p>
<p>I want to create a class, which is a set of objects that I created, that has attributes of its own.</p>
<p>The user experience I am thinking of is the following:</p>
<p>(let's say A, B, and C are Objects in memory)</p>
<p>sage: D = Box((A,B,C))</p>
<p>I want to be able to say <code>for i in D: ....</code></p>
<p>But I can't. </p>
<p>Any tips?</p>
http://ask.sagemath.org/question/9381/make-class-iterable/?answer=14100#post-id-14100The 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):`
Tue, 02 Oct 2012 20:40:50 -0500http://ask.sagemath.org/question/9381/make-class-iterable/?answer=14100#post-id-14100