Is there a way in Python to initialize a variable so that it will work with += "a string" or with += 100?
For example:
a = <what to put here>
a += 100 # a = 100
b=<same what to put here from above>
b+="a string" # b = "a string"
If I use:
a = ""
a += "a string" # this will work fine
b = ""
b += 0 # -> TypeError
Once the type of the variable has been defined, it is okay to get a TypeError afterwards if I try to += a different type. For example:
a = <what to put here>
a += "a string" # a = "a string"
a += 200 # -> okay to get a TypeError here
I’m only interested in making this work for ints and strings.
>Solution :
a = type('', (), {'__add__': lambda _, x: x})()
a += 100
b = type('', (), {'__add__': lambda _, x: x})()
b += "a string"
print([a, b])
Output (Attempt This Online!):
[100, 'a string']