How can a Python subclass control what data is stored in an immutable instance?


For this, at first understand what is __new__() method in Python. When subclassing an immutable type, override the __new__() method instead of the __init__() method.

The __new__ method gets called when an object is created whereas the __init__ method will be called to initialize the object. These are magic methods.

The magic methods that allow us to do some pretty neat tricks in object-oriented programming. They are also called Dunder methods. These methods are identified by two underscores (__) used as prefix and suffix.

Display the magic methods inherited by int class

Example

Using the fir(), we can print the 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']

The __init__()

Example

Let us see an example of the __init__() magic method to instantiate object −

class String: # The magic method to initiate object def __init__(self, string): self.string = string # Driver Code if __name__ == '__main__': # object creation myStr = String('Demo') # print object location print(myStr)

Output

<__main__.String object at 0x7f34c97799d0>

Subclassing an immutable type

Example

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

from datetime import date class FirstOfMonthDate(date): "Always choose the first day of the month" def __new__(cls, year, month, day): return super().__new__(cls, year, month, 1) class NamedInt(int): "Allow text names for 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 str to 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) # Calling print(FirstOfMonthDate(2022, 9, 8)) print(NamedInt('fifteen')) print(NamedInt(18)) # Create a URL path print(TitleStr('course for beginners'))

Output

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

Updated on: 19-Sep-2022

185 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements