Assume class Man
is defined within third-party file, which is not able to be directly modified:
class Man:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hi, I'm {self.name}.")
I want some objects behave differently when called greet
method.
For example, they speak "Hello" rather than "Hi" when greeting.
There are codes calling greet
in the third-party file, and I want to change their behaviour.
Here's what I did:
def another_greet(self):
print(f"Hello, I'm {self.name}.")
man = Man("Sue")
man.greet() # output: "Hi, I'm Sue"
man.greet = another_greet
man.greet() # TypeError: another_greet() missing 1 required positional argument: 'self'
man.greet(man) # output "Hello, I'm Sue"
However, after the replacing man.greet = another_greet
, it's not able to call greet
by man.greet()
, since the self
parameter cannot be automatically passed with the object itself. I have to call the method with extra explicit parameter, like man.greet(man)
, but I can't change the man.greet()
s in the third party files.
Intuitively I guess there's a way to do it, maybe some tricks on another_greet
is needed?
Inheritance does solve the question at a certain level. But in practice the object is not declared by me but given by third-party function, so I cannot initialize it as ModifiedMan. Anyway, it's true I can replace it with another ModifiedMan object, taking all its original parameters, yet the practical class is more complex the simply Man and not easy to initialize, doing this introduces much redundant code.