R2-D2
R2-D2

Reputation: 1624

What is object() good for?

How is it possible that

class EmptyClass:
    def __init__(self):
        pass

e = EmptyClass()
e.a = 123

works and:

o = object()
o.a = 123

does not (AttributeError: 'object' object has no attribute 'a') while

print isinstance(e, object)
>>> True

?

What is object() good for then, when you cannot use it like this?

Upvotes: 20

Views: 10477

Answers (1)

user2555451
user2555451

Reputation:

You cannot add attributes to an instance of object because object does not have a __dict__ attribute (which would store the attributes). From the docs:

class object

Return a new featureless object. object is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments.

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

And object does have its uses:

  1. As stated above, it serves as the base class for all objects in Python. Everything you see and use ultimately relies on object.

  2. You can use object to create sentinel values which are perfectly unique. Testing them with is and is not will only return True when an exact object instance is given.

  3. In Python 2.x, you can (should) inherit from object to create a new-style class. New-style classes have enhanced functionality and better support. Note that all classes are automatically new-style in Python 3.x.

Upvotes: 27

Related Questions