How to make a Python subclass control the data stored in an immutable instance?

How do I give a Python subclass control over the data stored in an immutable instance?

First, understand the new() method in Python. When subclassing an immutable type, override the new() method instead of the init() method.

The new method is called when an object is created, while the init method is called to initialize the object. These are magic methods.

Magic methods allow us to do some really cool tricks in object-oriented programming. They are also known as dunder methods. These methods are identified by two underscores (__) as a prefix and suffix.

Shows magic methods inherited from the int class

Example

Use fir() to print magic methods –

print(dir(int))

Output

['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__',
'__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__',
'__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__'
, '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__',
 '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__',
'__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__',
'__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__',
'__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate',
'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

init()

Example

Let’s look at an example of instantiating an object using the init() magic method. –

class String:
# Magic method to initialize the object
def __init__(self, string):
self.string = string

# Driver code
if __name__ == '__main__':
# Create the object
myStr = String('Demo')
# Print the object location
print(myStr)

Output

<__main__.String object at 0x7f34c97799d0>

Subclassing Immutable Types

Example

Now, let’s see how a Python subclass can control the data stored in an immutable instance.

from datetime import date

class FirstOfMonthDate(date):
"Select the first day of the month"
def __new__(cls, year, month, day):
return super().__new__(cls, year, month, 1)

class NamedInt(int):
"Text name using some numbers"
xlat = {'zero': 0, 'one': 1, 'ten': 10, 'fifteen': 15}
def __new__(cls, value):
value = cls.xlat.get(value, value)
return super().__new__(cls, value)

class TitleStr(str):
"Convert a string into a name suitable for a URL path"
def __new__(cls, s):
s = s.lower().replace(' ', '-')
s = ''.join([c for c in s if c.isalnum() or c == '-'])
      return super().__new__(cls, s)

# call
print(FirstOfMonthDate(2022, 9, 8))
print(NamedInt('fifteen'))
print(NamedInt(18))

#Create URL path
print(TitleStr('course for beginners'))

Output

2022-09-01
15
18
course-for-beginners

Leave a Reply

Your email address will not be published. Required fields are marked *