can't add variables to instances of built-in classes
Peter Otten
__peter__ at web.de
Sun Jul 17 07:40:31 EDT 2016
Kent Tong wrote:
> Hi,
>
> I can add new variables to user-defined classes like:
>
>>>> class Test:
> ... pass
> ...
>>>> a=Test()
>>>> a.x=100
>
> but it doesn't work if the instances belong to a built-in class such as
> str or list:
>
>>>> a='abc'
>>>> a.x=100
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> AttributeError: 'str' object has no attribute 'x'
>
> What makes this difference?
By default custom classes have a dictionary (called __dict__) to hold these
attributes. If for every string or integer there were such a dict that would
waste a lot of memory. You can subclass if you need it:
>>> class Str(str): pass
...
>>> s = Str("hello")
>>> s.x = 42
>>> s
'hello'
>>> s.x
42
You can also avoid the dict in your own classes by specifiying slots for
allowed attributes:
>>> class Test:
... __slots__ = ("foo", "bar")
...
>>> t = Test()
>>> t.foo = 42
>>> t.baz = "whatever"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'baz'
Use this feature sparingly, only when you know that there are going to be
many (millions rather than thousands) of Test instances.
More information about the Python-list
mailing list