Take a look at this code:
class SomeClass:
def __init__(self):
self._value = 'Hello, World!'
def func(self):
return self._value
instance = SomeClass()
print(instance.func())
def new_func(self):
return self._value + '!!!!!'
instance.func = new_func
print(instance.func())
This code creates an instance of SomeClass, calls original func, then overrides this function and calls it again.
I want to override a function in a single instance of a class, but not in the entire class so all the instances got the function overrided.
I expect this code to print:
Hello, World!
Hello, World!!!!!
But it prints:
Hello, World!
Traceback (most recent call last):
File "test.py", line 17, in <module>
print(instance.func())
TypeError: new_func() missing 1 required positional argument: 'self'
The self argument is not passed to the overrided function. Why? Aren't SomeClass.func(instance) and instance.func() the same?
How to override the function correctly so I can access the self argument in the overrided function?