Why can't I assign to undeclared attributes of an object() instance but I can with custom classes?

StackOverflow https://stackoverflow.com/questions/3654669

  •  01-10-2019
  •  | 
  •  

Question

Basically I want to know why this works:

class MyClass:
  pass

myObj = MyClass()
myObj.foo = 'a'

But this returns an AttributeError:

myObj = object()
myObj.foo = 'a'

How can I tell which classes I can use undefined attributes with and which I can't?

Thanks.

Was it helpful?

Solution

You can set attributes on any class with a __dict__, because that is where they are stored. object instances (which are weird) and any class that defines __slots__ do not have one:

>>> class Foo(object): pass
...
>>> foo = Foo()
>>> hasattr(foo, "__dict__")
True
>>> foo.bar = "baz"
>>>
>>> class Spam(object):
...     __slots__ = tuple()
...
>>> spam = Spam()
>>> hasattr(spam, "__dict__")
False
>>> spam.ham = "eggs"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Spam' object has no attribute 'ham'
>>>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top