To start off, this is not a question for how to get a specific result, but rather about the inner workings of Python. I am pretty new to programming, so please tell me if I am using any terms incorrectly. My hypothetical is centered around a pretty rudimentary error. I try to run:
"My age is " + 46
Obviously this gives the "Can't convert 'int' object to str implicitly" error. There is no definition for adding a string to an integer, but can I create one?
My first question is whether this is possible for built-in classes like strings and integers. I looked around and don't think that it is, but if anyone knows of a way I would be interested.
My second question is if I define two new classes that behave like strings and integers in every way, but are not built-in, can I define the addition of the two classes? I know I can define the addition of the same class, but what about two different ones?
In the end, addition (whether it is directly strings and integers or two classes like strings and integers) should produce: "My age is 46" by converting the integer to a string before adding it.
Thanks in advance!
As for your first question: it's essentially impossible to alter built-in classes. Although you can mess with other classes that is generally a terrible idea. Instead, you can make a subclass that has the property that you want.
For example:
class mystr(str):
def __add__(self, other):
return mystr(str(self) + str(other))
This code inherits all properties from the str
class, except for the one we want to change, namely its addition behavior. By casting self
to str
we still delegate to str
's addition, but we also cast the other argument to str
to get the behavior you described.
Finally, we cast back to mystr
so that we don't end up with a str
.
Now we can do the following:
>>> some_string = mystr("abc")
>>> some_string + 4
"abc4"