Today we’re going to talk about something that might seem like a foreign language to some of you immutable classes in Python. But don’t freak out, because I’m here to break it down for ya in the most casual way possible.
First: what are immutable classes? Well, they’re just fancyy terms for objects that can’t be changed once they’ve been created. Think of them like a frozen pizza you can’t add any toppings or change the crust after it’s already baked and ready to eat.
Now, why would anyone want immutable classes? Well, there are actually quite a few benefits! For one thing, they make your code more efficient because they don’t require as much memory allocation since their values can’t be changed. They also help prevent errors caused by unexpected changes in data, which is especially important when working with large datasets or complex systems.
But enough about the technical stuff how to create immutable classes using Python! Here are a few examples:
Example #1: Creating an Immutable Class for Dates
Let’s say you want to create a class that always returns the first day of every month. You can do this by inheriting from the built-in datetime module and overriding its constructor method with your own custom logic. Here’s what it might look like:
# Importing the date class from the datetime module
from datetime import date
# Creating a new class called FirstOfMonthDate that inherits from the date class
class FirstOfMonthDate(date):
# Defining a new constructor method for the FirstOfMonthDate class
def __new__(cls, year, month, day=1):
# Calling the constructor method of the parent class (date) and passing in the arguments
return super().__new__(cls, year, month, day)
# The super() function allows us to access methods and attributes from the parent class
# The __new__() method is used to create a new instance of the class
# The arguments passed in are the year, month, and day values for the date
# The default value for day is set to 1, as we want the first day of every month
# The return statement ensures that the new instance is returned when the constructor is called
In this example, we’re inheriting from the built-in `datetime.date()` class and overriding its constructor method to always set the first day of every month (unless a specific day is provided).
Example #2: Creating an Immutable Class for Numeric Values with Aliases
Sometimes you might want to create immutable classes that allow users to use aliases instead of actual numbers. For example, let’s say we wanted to create a class called `NamedInt` that allows us to use names like “zero” or “one” instead of the actual integer values:
# Creating a class called NamedInt that allows for the use of aliases instead of actual integer values
class NamedInt(int):
# Dictionary to store aliases and their corresponding integer values
xlat = {'zero': 0, 'one': 1}
# Function to create a new instance of the class
def __new__(cls, value):
# Checking if the value is a string and if it exists in the xlat dictionary
if isinstance(value, str) and value in cls.xlat:
# If it does, return the integer value corresponding to the alias
return super().__new__(cls, cls.xlat[value])
# If not, return the integer value of the input
return super().__new__(cls, int(value))
In this example, we’re inheriting from the built-in `int()` class and overriding its constructor method to allow users to use aliases instead of actual numbers (if they choose). If a string is provided that matches one of our predefined aliases, we convert it to an integer using the xlat dictionary. Otherwise, we just pass it along as-is to the `int()` constructor.
Example #3: Creating an Immutable Class for URL Paths
Finally, let’s say you want to create a class that converts strings into URL paths with specific formatting rules (e.g., lowercase letters and hyphens instead of spaces). Here’s what it might look like:
# Creating a class called TitleStr that inherits from the str class
class TitleStr(str):
# Defining a new method that takes in the class and a string as parameters
def __new__(cls, s):
# Using the super() function to call the __new__ method of the parent class (str)
# Converting the string to lowercase and replacing spaces with hyphens
# Returning the result as a new instance of the TitleStr class
return super().__new__(cls, s.lower().replace(' ', '-'))
In this example, we’re inheriting from the built-in `str()` class and overriding its constructor method to convert any input string into a URL path with lowercase letters and hyphens instead of spaces.
And that’s it! You now have three examples of how to create immutable classes using Python.