2

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.

Jacob Lyles
  • 9,920
  • 7
  • 32
  • 30

1 Answers1

2

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'
>>>
Katriel
  • 120,462
  • 19
  • 136
  • 170