ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Wed, 03 Oct 2012 05:55:59 +0200make class iterablehttps://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?
Wed, 03 Oct 2012 03:14:12 +0200https://ask.sagemath.org/question/9381/make-class-iterable/Answer 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>
https://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):`
Wed, 03 Oct 2012 03:40:50 +0200https://ask.sagemath.org/question/9381/make-class-iterable/?answer=14100#post-id-14100Answer 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>
https://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]
Wed, 03 Oct 2012 05:55:59 +0200https://ask.sagemath.org/question/9381/make-class-iterable/?answer=14101#post-id-14101