
PYTHON — Subclassing Immutable Built-in Types In Python
Software is a great combination between artistry and engineering. — Bill Gates
Insights in this article were refined using prompt engineering methods.

PYTHON — Overview of the Map Function in Python
# Subclassing Immutable Built-in Types in Python
In Python, you can subclass immutable built-in types such as float, int, and tuple. This means you can create a custom class that inherits the characteristics of the built-in types and add your own functionality to it. In this tutorial, we'll explore how to subclass the float type to create a Distance class that includes an additional attribute to store the unit of measurement.
Subclassing float with .__new__()
When subclassing an immutable built-in type, traditional methods like .__init__() may not work as expected. To overcome this, you can use the .__new__() method to initialize the object at creation time.
Here’s an example of how to subclass the float type to create a Distance class:
class Distance(float):
def __new__(cls, value, unit):
instance = super().__new__(cls, value)
instance.unit = unit
return instanceIn this code, .__new__() is used to create a new instance of the class cls by calling super().__new__(). The value argument is passed to the superclass float.__new__() to create and initialize the instance, and then the method customizes the new instance by adding a .unit attribute to it.
Now, the Distance class allows you to use an instance attribute for storing the unit in which you’re measuring the distance, and you can change its value at any time. Additionally, the dir() function reveals that your class inherits features and methods from float.
Example Usage of Distance Class
distance = Distance(10, "km")
print(distance) # Output: 10.0
print(distance.unit) # Output: 'km'
distance.unit = "miles"
print(distance.unit) # Output: 'miles'Proper Unit Conversion
It’s important to note that the Distance class in this example does not provide a proper unit conversion mechanism. This means that something like Distance(10, "km") + Distance(20, "miles") won't attempt to convert units before adding the values.
If you’re interested in unit conversion, you can explore projects like Pint on PyPI to enhance the functionality of your custom Distance class.
Conclusion
In this tutorial, you learned how to subclass immutable built-in types in Python, specifically by subclassing the float type to create a Distance class with an additional attribute to store the unit of measurement. Subclassing immutable built-in types can be useful in scenarios where you need to extend the functionality of the existing built-in types to suit your specific requirements.







