new-style classes and len method

Ben C spamspam at spam.eggs
Thu Apr 13 10:27:27 EDT 2006


On 2006-04-13, Thomas Girod <girodt at gmail.com> wrote:
> 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 ???

You can use cls in a classmethod to refer to the class. You can use any
name you want (well so long as it's not a "reserved word" I suppose).
The same is true of self, it's just a param name (quite unlike
JavaScript's "this"...).

But I don't think it makes sense for clear to be a classmethod, since
you presumably want a method that clears instances of lists?

The error is because you're trying to take the len of the class itself,
not the len of an instance of it.

What you had before was OK. Although you don't need to write the loop,
just del self[:] will do, and you can leave out the return statement if
you want.



More information about the Python-list mailing list