a question on __slots__ (and example from Nutshell)

Larry Bates lbates at swamisoft.com
Wed Jun 2 18:30:59 EDT 2004


I'll bet this is because you are subclassing Rectangle
class that is an old-style class.  Maybe one of the
other "experts" on this can confirm.

Larry Bates
Syscon, Inc.

"Porky Pig Jr" <porky_pig_jr at my-deja.com> wrote in message
news:56cfb0e3.0406021358.3d50d921 at posting.google.com...
> Hello, I"m still learning Python, but going through the Ch 5 OOP of
> Nutshell book. There is discussion on __slots__, and my understanding
> from reading this section is that if I have a class Rectangle (as
> defined in some prior sections), and then I provide definition
>
> class OptimizedRectangle(Rectangle):
>      __slots__ = 'width', 'heigth'
>
> I can use the instance of OptimizedRectangle, say, x, with 'width' and
> 'heigth', but (quoting the book) 'any attempt to bind on x any
> attribute whose name is not in C.__slots__ raises an exception.
>
> Alas, something goes wrong here, but I *can* bind any arbitrary
> attribute, and seems like the instance of OptimizedRectangle does have
> its own __dict__ where those attributes are kept. I'm using the latest
> stable version of Python (2.3.4, I believe). Here is a session from
> IDLE:
>
> Here I'm defining the class with __slots__:
>
> >>> class OptimizedRectangle(Rectangle):
> __slots__ = 'width', 'heigth'
>
>
> and create its instance, 'ropt':
> >>> ropt = OptimizedRectangle(4,5)
>
> Note that __dict__ is still there:
> >>> ropt.__dict__
> {}
>
> so I can define some arbitrary variable, say, newarea:
>
> >>> ropt.newarea = 15
>
> which goes into the dictionary
>
> >>> ropt.__dict__
> {'newarea': 15}
>
> whereas width and heigth are still kept in __slots__:
> >>> ropt.__slots__
> ('width', 'heigth')
>
> My impression is that once __slots__ are defined, __dict__ is
> effectively disabled - but in this example it's alive and well. Am I
> missing anything here?
>
> TIA.





More information about the Python-list mailing list