Dynamic object attribute creation

Ian Kelly ian.g.kelly at gmail.com
Mon Feb 29 11:33:48 EST 2016


On Mon, Feb 29, 2016 at 9:06 AM, Random832 <random832 at fastmail.com> wrote:
> On Mon, Feb 29, 2016, at 10:36, ast wrote:
>> but why doesn't it work with built-in classes int, float, list.... ?
>>
>> L = [1, 8, 0]
>> L.test = 'its a list !'
>>
>> (however lists are mutable, int, float ... are not)
>
> Because those classes do not have attribute dictionaries, in order to
> save space.
>
> You can make a class without an attribute dictionary, by using
> __slots__.

You can also make a list that does have an attribute dictionary by
subclassing it.

>>> class MyList(list): pass
...
>>> obj = MyList()
>>> obj.test = 'foo'



More information about the Python-list mailing list