“works on” isn’t meaningful language to describe the behaviour.
str
, by default, is a built-in type, not a “method”. Calling it - like calling any other type, such as the user-defined ones created with the class
statement - creates a new instance of the type (this behaviour can be altered using __new__
). The code that you show doesn’t modify the built-in type; it creates a new type and reuses the name for that new type. So of course existing objects of the type aren’t affected, and of course subsequent literals aren’t affected - when they’re created, their type is known directly, and is not looked up by name.
Syntax like this makes no sense because the purpose of the class
statement fundamentally is to create new types, not to modify existing ones.
Aside from that, anything that tries to make literals use a different type from their usual built-in one is a non-starter, because objects get created and “frozen” as part of compiling the code for functions.
What you seem to actually want is to be able to add methods to the built-in types. That is called “monkey-patching”, as noted:
Actual monkey-patching looks fundamentally different. It is supported already in Python for user-defined types:
class Example:
pass
x = Example()
try:
x.method()
except AttributeError:
print('the method does not exist.')
# Recall, the name "self" is only a convention. Written outside the class,
# that name isn't so meaningful.
def method(instance):
print('calling the method on', instance)
# monkey-patch the method.
Example.method = method
# Now it can be looked up from an instance, whether created prior:
x.method()
# or later:
Example().method()
However, it is not supported for built-in types, for good reason. Aside from causing untold potential for confusion (suppose I import
your library and now suddenly 1 + 1
literally doesn’t give 2
any more! And how am I meant to undo the effect?), it would require forgoing a huge suite of optimizations that take advantage of the fact that these built-in types are always exactly what the documentation says they are. In particular, methods on builtin types don’t need to be looked up by the usual attribute-lookup mechanisms; behind-the-scenes code can directly call the appropriate implementation function.