On 29/07/11 17:12, Ciantic wrote: >>>> class MyObject(object): > ... pass > ... >>>> my = MyObject() >>>> my.myvar = 'value' # No error! >>>> >>>> obj = object() >>>> obj.myvar = 'value' # Causes error! > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > AttributeError: 'object' object has no attribute 'myvar' > > Why simple inheritance from object does not cause errors at setattr, > yet direct init of object() does? > > > I was trying to "decor" objects, lists etc with own attributes that > could be used in templates and was sadly not permitted to do so: > >>>> something = [1,2] >>>> something.myvar = 'value' > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > AttributeError: 'list' object has no attribute 'myvar' > > (I could "solve" this by inheriting from list, but there are cases > where I can't do so, the data is coming elsewhere and wrapping it is > ugly, adding new attribute would be neater) > > But my question now is why this setattr problem happens on some types? > What are the types that usually does not allow to arbitrary setattr?
object has pre-defined slots (instead of just storing everything is a __dict__) -- so can your objects: Python 3.2.1 (default, Jul 11 2011, 12:37:49) [GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> class Foo: ... __slots__ = ['a', 'b'] ... >>> f = Foo() >>> f.a = 1 >>> f.b = 1 >>> f.c = 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Foo' object has no attribute 'c' >>> - Thomas -- http://mail.python.org/mailman/listinfo/python-list