Python object()
Function
The object()
function is the most basic built-in function in Python. It returns a featureless object that is the base for all new-style classes.
In Python, object
is the top-most class in the class hierarchy. All classes inherit directly or indirectly from this base class.
Syntax
object()
Parameters:
- None
Returns:
- A new featureless object instance.
Example: Create a Blank Object
obj = object()
print(type(obj))
<class 'object'>
Why Use object()
?
- Used as a base class in custom class definitions.
- Helps define immutable and minimal objects.
- Essential when creating classes in modern Python (new-style classes).
Example: Inheriting from object
Although it's optional in Python 3, you can explicitly inherit from object
to define a class:
class MyClass(object):
pass
instance = MyClass()
print(isinstance(instance, object))
True
Use Case: Ensuring Consistent Inheritance
Explicitly using object
helps ensure consistent method resolution order (MRO), especially in multiple inheritance scenarios.
Attributes of object()
Although featureless, object()
still has some basic methods:
__str__()
__repr__()
__eq__()
__hash__()
Common Mistakes
- Modifying the returned object from
object()
– You can't add attributes to it directly. - Confusing
object()
with instantiating a usable structure – It’s only meant as a base type.
Interview Tip
In interviews, understanding that all Python classes inherit from object
is important. It affects how methods like __init__
and __str__
behave in inheritance.
Summary
object()
creates a minimal base object.- It is the ancestor of all Python classes.
- Mostly used for inheritance and class hierarchies.
Practice Problem
Create a custom class that inherits from object
and adds a method to greet.
class Greeter(object):
def greet(self):
return "Hello from object!"
obj = Greeter()
print(obj.greet())
Hello from object!
This shows how even a basic class built from object
can be extended for real use.