avatarLaxfed Paulacy
# Summary

This article discusses how to subclass immutable built-in types in Python, such as `float`, to create custom classes with additional attributes and functionalities, exemplified by a `Distance` class that includes a unit of measurement.

# Abstract

The article titled "PYTHON — Subclassing Immutable Built-in Types In Python" delves into the concept of subclassing immutable built-in types like `float`, `int`, and `tuple`. It emphasizes the use of the `.__new__()` method for proper initialization of such subclasses, as opposed to the `.__init__()` method, which is ineffective for immutable types. The author provides a detailed example of a `Distance` class that extends the `float` type, incorporating a `.unit` attribute to represent the unit of measurement. The article also touches on the importance of proper unit conversion, suggesting the use of libraries like Pint for advanced functionality, and concludes by highlighting the practicality of subclassing immutable types to tailor them to specific needs.

# Opinions

- The author suggests that software development is a blend of artistry and engineering, indicating a reverence for the craftsmanship involved in programming.
- The use of prompt engineering methods to refine insights in the article implies a commitment to precision and clarity in technical writing.
- The article conveys that subclassing immutable built-in types can be a powerful technique in Python, allowing for the creation of more specialized and contextually relevant classes.
- It is implied that adding an additional attribute to a subclassed immutable type, such as the `.unit` attribute in the `Distance` class, can significantly enhance the utility of the original type.
- The author acknowledges the limitations of the `Distance` class example, particularly its lack of built-in unit conversion capabilities, and suggests exploring external libraries for comprehensive solutions.

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 instance

In 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.

PYTHON — Overriding Subclass Properties in Python

Subclassing
Immutable
Built In
Types
Python
Recommended from ReadMedium