0

Why is it possible to dynamically define a new attribute for every class instance in Python as long as it's not of type object?

class NewStyle(object):
    pass

class OldStyle:
    pass

a = object()
# This line raises AttributeError
a.foo = 1

# All of these work fine
a = Exception()
a.foo = 1

a = OldStyle()
a.foo = 1

a = NewStyle()
a.foo = 1

This behaviour seems to be identical in Python 3

reish
  • 831
  • 7
  • 18

1 Answers1

2

From the python doc:

Note: object does not have a __dict__, so you can’t assign arbitrary attributes to an instance of the object class.

Some class definition provide a __dict__ attribute and then it is included in instances by default.

See also __slots__

fredtantini
  • 15,966
  • 8
  • 49
  • 55