I am running into an issue with subtyping the str class because of the str.__call__ behavior I apparently do not understand.
This is best illustrated by the simplified code below.
class S(str):
def __init__(self, s: str):
assert isinstance(s, str)
print(s)
class C:
def __init__(self, s: str):
self.s = S(s)
def __str__(self):
return self.s
c = C("a") # -> prints "a"
c.__str__() # -> does not print "a"
str(c) # -> asserts fails in debug mode, else prints "a" as well!?
I always thought the str(obj) function simply calls the obj.__str__ method, and that's it. But for some reason it also calls the __init__ function of S again.
Can someone explain the behavior and how I can avoid that S.__init__ is called on the result of C.__str__ when using the str() function?