Subclassing Immutables

Now, if you’ve been living under a rock for the past decade or so, let me fill you in on what this whole “immutability” thing is all about.

Basically, an object is considered immutable if its value cannot be changed once it has been created. This means that any attempt to modify such an object will result in a new object being created with the modified values.In Python, some of the built-in data types like strings and tuples are immutable by default.

But what happens when you want to create your own custom immutable objects? Well, my friend, that’s where subclassing comes in! By inheriting from an existing immutable object (like a tuple or string), we can create our very own immutable class with all the benefits of immutability.

Here’s how it works: let’s say you want to create a custom immutable data type called “Person” that contains a name and age. You could do something like this:

# Creating a custom immutable class called "Person" that contains a name and age
class Person(tuple): # Defining the class "Person" and inheriting from the built-in "tuple" class
    def __new__(cls, name, age): # Defining a new method "__new__" that takes in the class "cls", name, and age as parameters
        return super().__new__(cls, (name, age)) # Calling the parent class's "__new__" method to create a new instance of the "Person" class with the given name and age

    def __repr__(self): # Defining a new method "__repr__" that takes in the instance "self" as a parameter
        return f"Person({self[0]}, {self[1]})" # Returning a string representation of the "Person" instance with its name and age values

In this example, we’ve subclassed the built-in tuple class to create our own custom immutable “Person” object. The `__new__` method is called when a new instance of the class is created and allows us to override how that creation process works. In this case, we’re passing in two arguments (name and age) which are then wrapped up into a tuple using super().

The `__repr__` method is used to define how our custom object will be represented when printed or displayed in the console. By returning a string that includes the values of each field, we can easily see what data is contained within the object without having to manually inspect it.

Subclassing immutable objects in Python: easy as pie (or cake, if you prefer). And with this newfound knowledge, you’re ready to take on any custom immutability challenge that comes your way.

SICORPS