[Tutor] New Style Classes, __getitem__ and iteration
Marilyn Davis
marilyn at deliberate.com
Mon May 19 23:21:16 CEST 2008
Hi Tutors and Tutees,
I've been teaching Python quite a while and a brilliant student asked a
question that made me realize a big hole in my understanding.
I think it is really magical that, when I define __getitem__ on classic
classes, the built-in iterator uses it.
But, when I make the same class as a new style class, I lose this behavior.
I didn't realize that something was lost in defining a new style class.
Maybe it's something else that I'm missing.
Thank you for your insights.
Marilyn
p.s.
Here's some code that demonstrates my confusion:
#!/usr/bin/env python
class Circle:
def __init__(self, data, times):
"""Put the 'data' in a circle that goes around 'times' times."""
self.data = data
self.times = times
def __getitem__(self, i):
"""circle[i] --> Circle.__getitem__(circle, i)."""
l_self = len(self)
if i >= self.times * l_self:
raise IndexError, \
"Error raised: Circle object only goes around %d times"\
% self.times
return self.data[i % l_self]
def __len__(self):
return len(self.data)
class NewCircle(list):
def __init__(self, data, times):
list.__init__(self, data)
self.times = times
def __getitem__(self, i):
l_self = len(self)
if i >= self.times * l_self:
raise IndexError, \
"Error raised: NewCircle object only goes around %d times"\
% self.times
return list.__getitem__(self, i % l_self)
def main():
circle = Circle("around", 3)
print sorted(circle)
new_circle = NewCircle("around", 3)
print sorted(new_circle)
main()
"""
OUTPUT:
$ ./circle_question.py
['a', 'a', 'a', 'd', 'd', 'd', 'n', 'n', 'n', 'o', 'o', 'o', 'r', 'r',
'r', 'u', 'u', 'u']
['a', 'd', 'n', 'o', 'r', 'u']
$
"""
More information about the Tutor
mailing list