Edit, this previously said "This can't be done, since str is one of the immutable types in Python. Among the immutable types are bool, int, float, tuple, string, frozenset and perhaps a few more I don't know about."
However, that's incorrect - those are types for immutable objects, but str (as list and dict) are built-in types and are immutable types.
For example:
def append(self, *args, **kwargs):
print("not appending")
list.append = append
xs = []
xs.append(1)
Will cause the error:
TypeError: cannot set 'append' attribute of immutable type 'list'
So, although an object of type list is mutable, the type list itself is not mutable, unlike a type you might define yourself, or that was defined in one of the many packages in Python.
With other types, you might be able to do something like this:
class MyClass:
def __str__(self):
return "my class"
def print_me_quoted(self):
print(f'"{self}"')
mc_old = MyClass()
MyClass.print_me_quoted = print_me_quoted
mc_new = MyClass()
# both now have it
mc_old.print_me_quoted()
mc_new.print_me_quoted()
It's still a spectacularly bad idea, to change the behaviour of a class by monkey-patching it like this, but it can be done. Expect your editor or IDE not to like it, or to understand it - you'll see warnings.
If you try this with str:
def print_me_quoted(self):
print(f'"{self}"')
str.print_me_quoted = print_me_quoted
mc = str(10)
mc.print_me_quoted()
You get this TypeError:
TypeError: cannot set 'print_me_quoted' attribute of immutable type 'str'
You could do it on your own version of str:
class Str(str):
...
def print_me_quoted(self):
print(f'"{self}"')
Str.print_me_quoted = print_me_quoted
mc = Str(10)
mc.print_me_quoted()
But of course that does not change the standard behaviour of strings - which is exactly the point.
Strthat's a subclass ofstr, but don't call the subclass the same thing as the parent class, as it will only lead to confusion when reading your code, and you'll run into problems like this.self.wordsinstead ofself.works?strclass - the name "str" is not looked up in the process, there is absolutely nothing you can do from Python code to change this behavior.wordswas supposed to be used later. I should edit the post to avoid confusion. Thanks for the comment, @esramish.forbiddenfruitpackage (which basically knows how these types work).