Python object(): The Base Class for All Objects

object Example

The object() function creates a new empty object, which serves as the base for all Python classes. It’s useful for creating generic objects, inheritance, and custom class structures.

Example

obj = object()
print(obj)  
# Output:  (Memory address)

This creates a new generic object.

Syntax

object()
  • Returns → A new base object with no attributes or methods.

1. Using object() as a Placeholder

You can use object() as a dummy value when you need a unique placeholder.

NOT_SET = object()

def check_value(value):
    if value is NOT_SET:
        print("Value is not set")
    else:
        print("Value is:", value)

check_value(NOT_SET)  # Output: Value is not set

Unlike None, a new object() is always unique.

2. Creating a Custom Class from object

In Python 3, all classes inherit from object by default, but you can still define it explicitly.

class MyClass(object):
    pass

obj = MyClass()
print(isinstance(obj, object))  
# Output: True

Every Python class is automatically a subclass of object.

3. Understanding object() Methods

Since object is the base class, it inherits basic methods like:

obj = object()
print(dir(obj))

Returns methods like:

['__class__', '__delattr__', '__dir__', '__eq__', '__format__', '__hash__', ...]

These are default object methods.

4. Preventing Attribute Modification

An object() instance cannot have attributes assigned.

obj = object()
obj.name = "Test"  
# AttributeError: 'object' object has no attribute 'name'

This makes object() immutable.

Key Notes

  • Base class for all Python objects.
  • Can be used as a unique placeholder.
  • Does not support attribute assignment.
  • All Python classes inherit from object by default.

By using object(), you can create generic objects, structure class hierarchies, and ensure uniqueness in special cases. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top