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:
>>> obj = object()
>>> obj
<object object at 0x1079e6f90>
object
Constructor
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:
>>> empty_object = object()
>>> empty_object
<object object at 0x1079e6f90>
Note: Because object
is featureless, there are no literals for creating it, and it doesn’t support accessing or modifying values. It is immutable and doesn’t support value deletion.
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:
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.
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Python's Built-in Functions: A Complete Exploration (Tutorial)
- Python Constants: Improve Your Code's Maintainability (Tutorial)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)
- Python's Built-in Functions: A Complete Exploration (Quiz)
- Defining Python Constants for Code Maintainability (Course)