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?

1
  • This isn't weird behavior at all, subclasses can support additional attributes that the base class does not. Commented Oct 24, 2019 at 23:23

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for great info! Weird behavior by Python though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.