__slots__ query
Gustavo Cordova
gcordova at hebmex.com
Tue Apr 2 09:51:28 EST 2002
>
> I notice that in 2.2 it's possible to do strange things to slots via
> instances.
>
Strange to you, but pretty obvious to me:
1. You define a class with a specification of allowing
for two (only two) attribute slots, named "a" and "b":
> Thus
> >>> class A(object):
> ... __slots__ = ['a','b']
> ...
2. You instantiate such a class.
Note: The object you used to define which slots you
wanted was mutable, but after defining the class,
__slots__ may no longer be needed.
> >>> a=A()
> >>> a.c=2
> ===> error
> >>> a.__slots__.append('c')
> >>> a.c=2
> ===> error
> >>> a.__slots__
> ['a', 'b', 'c']
> >>> A.__slots__
> ['a', 'b', 'c']
> >>> b=A()
> >>> b.c=2
> ===> error
Seems pretty natural to me. I'd be alarmed if there
actually *was* a .c attribute.
The __slots__ object might be mutable, it doesn't
mean that you can add attributes anytime after
defining the class.
-gustavo
More information about the Python-list
mailing list