I’m trying to make a simple derived class based on str, with the addition of an instance variable, flag. For reasons I do not understand, I get an error if I try to pass the flag to the constructor:
>>> class Strvalue(str):
def __init__(self, content, flag=None):
str.__init__(self, content)
self.flag = flag
>>> Strvalue("No problem")
'No problem'
>>> Strvalue("Problem", flag=None)
Traceback (most recent call last):
File "<pyshell#113>", line 1, in <module>
Strvalue("Problem", flag=None)
TypeError: str() takes at most 1 argument (2 given)
I’ve checked that in the succesful calls, the Strvalue constructor really does get called– I haven’t mistyped __init__ or something of that sort. So what is going on?
Edit: According to this question (and @Martijn’s answer), the problem is avoided by overriding __new__ as well. The question was why this was happening.
You need to use
__new__instead of__init__when subclassingstr, see basic customization.Your code doesn’t override
str.__new__, so the originalstr.__new__constructor is called with your two arguments, and it only accepts one.strobjects are immutable, they construct a new instance in__new__, which then cannot be changed anymore; by the time__init__is called,selfis an immutable object, so__init__forstrdoesn’t make sense. You can still also define an__init__method, but since you already have__new__, there is really no need to divide the work up across two methods.