PEP idea. ( removing __slots__ )

Tim Peters tim.one at comcast.net
Sun Jul 6 23:54:48 EDT 2003


[Martin v. Löwis]
>> No. Some classes have slots for efficiency, and their subclasses
>> have dictionaries for generality.
>>
>> Likewise, some classes have slots to save the dictionary for most
>> instances, but some instances may need additional attributes, in
>> which case Python creates the dictionary on-the-fly.

[simon place]
> I know subclasses can add a __dict__, but i really thought a class
> with __slots__ could not have a __dict__,

It can, but if you want that (I have a hard time imagining why ...), you
have to give it a __dict__ explicitly.

> doesn't the script below show this behavior?

It shows that a class with __slots__ won't grow a __dict__ by magic
(although a subclass of a class with __slots__ can grow a __dict__ by magic,
provided that the subclass doesn't itself define __slots__).

> PythonWin 2.3b2 (#43, Jun 29 2003, 16:43:04) [MSC v.1200 32 bit
> (Intel)] on win32.
> Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au)
> - see 'Help/About PythonWin' for further copyright information.
>  >>> class A(object):
> ... 	__slots__=['a']
> ...
>  >>> b=A()
>  >>> b
> <__main__.A object at 0x00EFABF0>
>  >>> b.__dict__
> Traceback (most recent call last):
>    File "<interactive input>", line 1, in ?
> AttributeError: 'A' object has no attribute '__dict__'
>  >>> b.a
> Traceback (most recent call last):
>    File "<interactive input>", line 1, in ?
> AttributeError: a
>  >>> b.a=1
>  >>> b.a
> 1
>  >>> b.b=1
> Traceback (most recent call last):
>    File "<interactive input>", line 1, in ?
> AttributeError: 'A' object has no attribute 'b'

Constrast with:

>>> class A(object):
...     __slots__ = 'a', '__dict__'  # NOTE:  __dict__ explicitly given
...
>>> b = A()
>>> b
<__main__.A object at 0x006AD730>
>>> b.__dict__
{}
>>> b.a
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: a
>>> b.a = 1
>>> b.a
1
>>> b.b = 1
>>> b.b
1
>>>






More information about the Python-list mailing list