clearing subclassed lists/dicts
g2 at iowegian.com
g2 at iowegian.com
Thu May 30 14:38:07 EDT 2002
Hi All,
I've gotten interested in subclassing lists and dictionaries, and that got me
wondering if there's an elegant way to clear the contents of the underlying
type.
I tried a couple of things that I didn't really expect to work:
>>> class L(list):
... def clear(self):
... self = []
...
>>> l = L()
>>> type(l)
<class '__main__.L'>
>>> l.clear()
>>> type(l)
<class '__main__.L'>
>>> l.append(1)
>>> l
[1]
>>> l.clear()
>>> l
[1]
>>> class L2(list):
... def clear(self):
... del(self)
...
>>> l2 = L2()
>>> l2.append(1)
>>> l2.clear()
>>> l2
[1]
as well as one I was pretty sure would:
>>> class L3(list):
... def clear(self):
... while self:
... del(self[-1])
...
>>> l3 = L3()
>>> l3.append(1)
>>> l3.clear()
>>> l3
[]
And it did work, but it doesn't seem particularly elegant. Is there a better
way?
a-masochist-in-search-of-a-head-slap-ly y'rs,
=g2
More information about the Python-list
mailing list