object

The built-in object class is the most fundamental base class in Python from which all other classes are derived.

This class provides a minimal and featureless object that includes only the methods common to all Python objects. The object class is typically used to create unique sentinel values or as a base for custom classes:

Python
>>> obj = object()
>>> obj
<object object at 0x1079e6f90>

object Constructor

Python Syntax
object()

Arguments

  • The object() constructor doesn’t take arguments

Return Value

  • Returns a Python object instance

object Examples

Creating an instance of object by calling the constructor:

Python
>>> empty_object = object()
>>> empty_object
<object object at 0x1079e6f90>

object Methods

  • The object class has no public methods.

object Common Use Cases

The most common use cases for the object include:

  • Serving as a base class for all Python classes
  • Creating unique sentinel values for algorithms
  • Using as a placeholder for featureless or immutable objects

object Real-World Example

In practice, the object class is often used to create unique sentinel values. A sentinel value can be useful as a unique marker to signify the absence of a value or as a condition to stop an iterative or recursive algorithm. Consider the following example with a Circle class:

Python circle.py
SENTINEL = object()

class Circle:
    def __init__(self, radius):
        self.radius = radius
        self._diameter = SENTINEL

    @property
    def diameter(self):
        if self._diameter is SENTINEL:
            self._diameter = self.radius * 2
        return self._diameter

# Usage
circle = Circle(5)
print(circle.diameter)  # Output: 10

In this example, object() is used to create a sentinel value (SENTINEL) to determine if the diameter needs to be computed. This approach efficiently caches the computation and avoids unnecessary recalculations.

Tutorial

Object-Oriented Programming (OOP) in Python

In this tutorial, you'll learn all about object-oriented programming (OOP) in Python. You'll learn the basics of the OOP paradigm and cover concepts like classes and inheritance. You'll also see how to instantiate an object from a class.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 25, 2024 • Reviewed by Dan Bader