P
Porky Pig Jr
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__:
__slots__ = 'width', 'heigth'
and create its instance, 'ropt':
Note that __dict__ is still there:{}
so I can define some arbitrary variable, say, newarea:
which goes into the dictionary
{'newarea': 15}
whereas width and heigth are still kept in __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.
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__:
__slots__ = 'width', 'heigth'
and create its instance, 'ropt':
Note that __dict__ is still there:{}
so I can define some arbitrary variable, say, newarea:
which goes into the dictionary
{'newarea': 15}
whereas width and heigth are still kept in __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.