a question on __slots__ (and example from Nutshell)

Anand Pillai pythonguy at Hotpop.com
Thu Jun 3 04:38:05 EDT 2004


Since types and classes are unified in the new object model,
the following line at the top of the source file will also
do the trick, even if you dont directly subclass from object.

__metaclass__ = object

class Rectangle... etc

-Anand


"Ixokai" <usenet at ixokai.net> wrote in message news:<10bsls7skd4ul7e at corp.supernews.com>...
> The problem is that the __slots__ mechanism is a function of "new style
> classes", which really should be renamed =) A new-style-class is any class
> that inherits from "object" or one of its descendants.
> 
> You're inheriting from Rectangle. What is its definition? I bet its
> something like:
> 
>     class Rectangle:
>         def __init__(self): pass
> 
> Since OptimizedRectangle inherits from an old-style class, its an old-style
> class... and  __slots__ has no function.
> 
> So, just...
> 
>     class Rectangle(object): pass
> 
> And OptimizedRectangle should work like you expect.
> 
> --Stephen
> 
> "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