0

When I try to assign custom attribute on object instance, AttributeError is raised:

>>> o = object()
>>> o.hi = 'mom'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'

The same happens on most (all?) built-in types.

However, when I create instance of trivial object subclass, new property is succesfully created:

>>> class foobar(object): pass
... 
>>> o = foobar()
>>> o.hi = 'mom'
>>> o.hi
'mom'

Why is that happening? Should I make my classes reject custom attributes to match object behavior? If so, how could it be done?

  • 2
    Check this out: http://stackoverflow.com/q/1529002/1679863 – Rohit Jain Mar 18 '16 at 17:27
  • I don't think you should because there isn't really a reason to, but to do that, do this: `def __getattribute__(self, attr): raise AttributeError("{} object has no attribute {}".format(repr(self.__class__.__name__), repr(attr)))` – zondo Mar 18 '16 at 17:29
  • *"Should I make my classes reject custom attributes to match object behavior?"* - well, do you need to? – jonrsharpe Mar 18 '16 at 17:32

0 Answers0