Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How does Python class inherit objects?
In Python, all classes inherit from the base object class, but the syntax and behavior differ between Python 2.x and Python 3.x. Understanding this inheritance is crucial for working with modern Python code.
Python 2.x Class Styles
Python 2.x had two distinct class styles depending on inheritance ?
Old Style Classes
These classes have no built-in type as a base class ?
# This example shows Python 2 syntax (for reference only)
class OldFoo: # no base class
pass
print(OldFoo.__bases__)
()
New Style Classes
These classes explicitly inherit from object or another built-in type ?
class NewFoo(object): # directly inherit from object
pass
print(NewFoo.__bases__)
(<class 'object'>,)
Python 3.x Class Inheritance
Python 3.x simplified class inheritance by making all classes automatically inherit from object ?
class Foo: # implicitly inherits from object
pass
print(Foo.__bases__)
print(isinstance(Foo(), object))
(<class 'object'>,) True
Explicit vs Implicit Inheritance
Both syntaxes work identically in Python 3.x ?
# Implicit inheritance (recommended)
class ImplicitClass:
pass
# Explicit inheritance (optional)
class ExplicitClass(object):
pass
print("Implicit:", ImplicitClass.__bases__)
print("Explicit:", ExplicitClass.__bases__)
print("Same behavior:", ImplicitClass.__bases__ == ExplicitClass.__bases__)
Implicit: (<class 'object'>,) Explicit: (<class 'object'>,) Same behavior: True
Comparison
| Python Version | Class Style | Inheritance | Recommended |
|---|---|---|---|
| Python 2.x | Old Style | No base class | No |
| Python 2.x | New Style | Explicit object
|
Yes |
| Python 3.x | All classes | Implicit object
|
Yes |
Conclusion
In Python 3.x, all classes automatically inherit from object, eliminating the old style vs new style distinction. You can omit (object) in class definitions as inheritance is implicit.
