Why don't I need to call `super().__init__` in my `str` subclass?

For a coding challenge, I made a small subclass of str so I could store and extra attribute with a string:

class Node(str):
    def __init__(self, s):
        self.marked = False

    def __bool__(self):
        return self.marked

This way I could write Node('44') and have something that compares equally with a str but has a different truth value. l noticed though that I apparently don’t need to call super().__init__ in Node.__init__ for this to work. Why is that?

Most immutable types don’t do anything in __init__, because at that point the object’s already created and so they’d have to modify it to set the value. Instead it’s done in __new__. Since you didn’t override that it just also gets the string value and constructs your object with it.

1 Like