Inheriting from str

Jon Ribbens jon+usenet at unequivocal.eu
Mon Sep 20 10:27:13 EDT 2021


On 2021-09-20, ast <ast at invalid> wrote:
> Hello
>
> class NewStr(str):
>      def __init__(self, s):
> 	self.l = len(s)
>
> Normaly str is an immutable type so it can't be modified
> after creation with __new__
>
> But the previous code is working well
>
> obj = NewStr("qwerty")
> obj.l
> 6
>
> I don't understand why it's working ?

The string itself is immutable. If it's a subclass then it may have
attributes that are not immutable:

>>> s = 'hello'
>>> s.jam = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  AttributeError: 'str' object has no attribute 'jam'
>>> class foo(str): pass
...
>>> s = foo('hello')
>>> s.jam = 3
>>> s.jam
3

There's a lot of places in Python where you can break standard
assumptions with sufficiently evil or badly-written classes.
e.g.:

>>> class intt(int):
...   def __add__(self, other):
...     return int(self) + int(other) * 2
...
>>> a = intt(2)
>>> b = intt(3)
>>> a + b
8
>>> b + a
7



More information about the Python-list mailing list