Python
Programming
Object-oriented Programming
Python Classes
Python Syntax

What is the difference between old style and new style classes in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In the Python programming language, the concept of "classes" plays a critical role in supporting object-oriented programming. Classes are essentially blueprints for creating objects, and Python has evolved over time in how these blueprints can be defined and used. Significantly, this evolution brought about a distinction between "old-style" and "new-style" classes. Understanding this distinction is crucial for both Python 2 programmers and those dealing with legacy code in Python 3.

Definition and Historical Context

Old-style classes were the only type of class in Python until the introduction of new-style classes with Python 2.2. Any class that does not inherit from object (either directly or indirectly) is considered an old-style class. These classes were part of Python from its first release.

New-style classes were introduced to provide a unified object model with a full meta-model. They inherit from the base class object, either directly or through other new-style classes. This model was later refined and became the standard in Python 2.2 and all classes in Python 3 are new-style classes.

Key Differences

The introduction of new-style classes brought several enhancements over old-style classes. Some of the key differences include:

1. Type and Class Consistency

In old-style classes, types and classes were treated differently. Types were for built-in types like int, list, while classes were for user-defined types. This inconsistency was resolved with new-style classes, where types and classes were merged, and all new-style classes are of type type.

2. Descriptor Support

New-style classes support descriptors, which are a generalized way to customize attribute access and modify their behavior. This feature provides a means to define managed attributes, and is behind properties, class methods, and static methods.

3. Multiple Inheritance and the Method Resolution Order (MRO)

New-style classes use a more predictable and manageable algorithm (C3 linearization) to determine the method resolution order in case of multiple inheritance. This contrasts with the depth-first approach used in old-style classes, which could be inconsistent in complex inheritance scenarios.

4. __slots__

The __slots__ attribute is a feature of new-style classes that allow explicitly declaring instance attributes. Using __slots__ can lead to significant memory savings because it prevents the creation of instance dictionaries unless explicitly stated.

5. Enhanced Introspection Capabilities

New-style classes provide improved introspection capabilities. With new-style classes, you can use functions like dir(), type(), and isinstance() more reliably. The __class__ and type() for a new-style class instance are consistent, unlike with old-style classes.

6. Built-in super() Function

The super() function, used to call methods from a base class, works only with new-style classes. It simplifies calling base class methods by automatically handling the context and method resolution order.

Technical Example

Consider the following Python 2.x code demonstrating the difference in the method resolution order (MRO):

python
1class A(object):  # new-style class
2    def who(self):
3        return 'A'
4
5class B(A):  # new-style class
6    pass
7
8class C(A):  # new-style class
9    def who(self):
10        return 'C'
11
12class D(B, C):  # new-style class
13    pass
14
15print(D().who())  # prints 'C'

If A had been an old-style class, the MRO would be different, and depending on the structure, Python might have ended up calling A's who() method instead of C's.

Summary Table

FeatureOld-Style ClassesNew-Style Classes
InheritanceDo not inherit from objectInherits from object
IntrospectionLimitedEnhanced
Attribute ManagementNo __slots__Supports __slots__
Method Resolution OrderDepth-firstC3 Linearization
Type ConsistencyType and Class differentUnified type and class system

Conclusion

The shift to new-style classes in Python was a significant improvement that resolved many inconsistencies and limitations of old-style classes. Although Python 2 maintained backwards compatibility by retaining old-style classes, Python 3 exclusively uses new-style classes, making understanding these distinctions mostly relevant when dealing with legacy Python 2 code or migrating it to Python 3. In modern practice, always using new-style classes (implicitly done in Python 3) is advisable for the additional features and consistency they offer.


Course illustration
Course illustration

All Rights Reserved.