a question on __slots__ (and example from Nutshell)
Porky Pig Jr
porky_pig_jr at my-deja.com
Wed Jun 2 17:58:08 EDT 2004
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