setattr() on "object" instance

Ahmad Syukri b syockit at gmail.com
Mon Mar 16 01:39:45 EDT 2009


On Mar 16, 1:21 pm, Sean DiZazzo <half.ital... at gmail.com> wrote:
> Why is it that you can setattr() on an instance of a class that
> inherits from "object", but you can't on an instance of "object"
> itself?
>
> >>> o = object()
> >>> setattr(o, "x", 1000)
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: 'object' object has no attribute 'x'

I suppose you cannot set attributes to instances of any built-in
classes, i.e. int(), list() etc.

> >>> class Object(object):pass
> ...
> >>> o = Object()
> >>> setattr(o, "x", 1000)
> >>> o.x
>
> 1000
>
> I notice that the first example's instance doesn't have a __dict__.
> Is the second way the idiom?
>
> ~Sean

Since all classes inherit from object, I suppose the definition can be
as simple as 'class Object:pass', and assignment can be as simple as
'o.x = 1000'

A. Syukri



More information about the Python-list mailing list