0

The following code runs nicely with no error:

class A(object):
  pass

a = A()
a.attr = True

Running the following code:

o = object()
o.attr = True

raises the following error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-54-9fd7259047d0> in <module>()
      1 o = object()
----> 2 o.attr = True

AttributeError: 'object' object has no attribute 'attr'

Why? Class A inherited from object, so why do I get an error when I create an object from class object?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
user2725109
  • 2,286
  • 4
  • 27
  • 46

1 Answers1

1

According to W3Schools:

The object() function returns an empty object.

You cannot add new properties or methods to this object.

Running a quick type comparison:

>>> type(a)
<class '__main__.A'>
>>> type(o)
<class 'object'>

shows that a and o are fundamentally different.

From the Python documentation:

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

rassar
  • 5,412
  • 3
  • 25
  • 41