new-style classes and len method

Paul McGuire ptmcg at austin.rr._bogus_.com
Thu Apr 13 10:24:44 EDT 2006


"Thomas Girod" <girodt at gmail.com> wrote in message
news:1144936961.203493.169840 at v46g2000cwv.googlegroups.com...
> Hi there.
>
> I'm trying to use new-style classes, but there is something i'm
> obviously missing
>
> here it is :
>
> class Data(list):
>     __slots__ = ["width", "height", "label"]
>
>     def __init__(self,width,height,label=None):
>         list.__init__(self)
>         self.width = width
>         self.height = height
>         self.label = label
>
>     def clear(cls):
>         while len(cls) > 0: del cls[0]
>         return
>     clear = classmethod(clear)
>
> #> d = Data(2,2)
> #> d.clear()
> TypeError: len() of unsized object
>
> off course it was working with :
>
> [...]
>     def clear(self):
>         while len(self) > 0: del self[0]
>         return
>
> So, I guess you can't use "cls" as a replacement for "self". So, what
> do I have to use ???
>

Um, why do you think clear() needs to be a classmethod?  Isn't it supposed
to work on an instance of Data?  If you just remove that "clear =
classmethod(clear)" statement, I think this works as you expect.

(Although your implementation of clear() will work correctly, you might
consider the more efficient "del self[:]" slice operation, instead of your
while loop.)





More information about the Python-list mailing list