setattr() on "object" instance

Aahz aahz at pythoncraft.com
Thu Mar 26 00:17:26 CET 2009


In article <33f40372-13fb-4d52-921d-8ab00685c9f6 at q30g2000prq.googlegroups.com>,
Sean DiZazzo  <half.italian 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'
>
>>>> 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?

>>> class C(object):
...     __slots__ = []
... 
>>> x = C()
>>> x.foo = 'bar'
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'C' object has no attribute 'foo'
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"At Resolver we've found it useful to short-circuit any doubt and just
refer to comments in code as 'lies'. :-)"
--Michael Foord paraphrases Christian Muirhead on python-dev, 2009-3-22



More information about the Python-list mailing list