Python 3.1, object, and setattr()
Steve Howell
showell30 at yahoo.com
Thu Apr 1 10:16:26 EDT 2010
On Apr 1, 6:46 am, Ethan Furman <et... at stoneleaf.us> wrote:
> Greetings!
>
> Perhaps I woke up too early this morning, but this behaviour has me baffled:
>
> Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>
> --> test = object()
>
> --> setattr(test, 'example', 123)
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> AttributeError: 'object' object has no attribute 'example'
>
> Shouldn't setattr() be creating the 'example' attribute? Any tips
> greatly appreciated!
>
On 2.6.2 the error seems to be limited to instances of object. If you
subclass object, you are fine. I do not know why that is so; I'm just
verifying that the behavior you see is not limited to 3.1.1.
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more
information.
>>> class Foo(object): pass
...
>>> test = Foo()
>>> setattr(test, 'example', 123)
>>> test.example
123
>>> test = object()
>>> setattr(test, 'example', 123)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'example'
It's probably good to subclass object anyway, with something like:
class Record(object):
pass
But I do not know your use case.
More information about the Python-list
mailing list