The function is Python Inside “ First class citizen ”, It can be passed and referenced like a variable , for example :
def hhh():
print("hhh")
def ddd():
print("ddd")
hhh=ddd
hhh()
Output :
ddd
hhh Function is ddd The function replaces .
Monkey patch is a method of replacing functions in a class , You can dynamically modify the functions in the class :
class Test:
def func(self):
print("hi")
def monkey(self):
print("hi monkey")
Test.func=monkey
a=Test()
a.func()
Output :
hi monkey
We defined the monkey patch monkey( You can also take another name ) function , Receive a parameter , Note that the replacement is the instance method of the class , So the first parameter is the instance object itself , Usually take self, It's OK to take another name .monkey The number of parameters of the function does not necessarily need to be the same as that to be replaced func The functions are the same , Can be more , But pay attention to press... When calling after replacement monkey The number of parameters of the function is passed to the parameter .
class Test:
def func(self):
print("hi")
def monkey(self,a):# The number of parameters does not have to be the same as func Agreement
print(self)# Print out <__main__.Test object at 0x7fb5cef7d5b0>, You can see that it is the class instance object itself
print("hi monkey")
a=Test()
Test.func=monkey# Substitution can occur after instantiation
a.func(3)# because monkey The number of parameters of the function has been increased by one , So pass one more
Output :
<__main__.Test object at 0x7fb5cef7d5b0>
hi monkey
You can also replace func function :
class Test:
def func(self):
print("hi")
def monkey(self,a):
print(self)
print("hi monkey")
a=Test()
a.func=monkey# Replace the func function
a.func(a,3)# But at this time, you need to explicitly pass the instance itself as the first parameter
Output :
<__main__.Test object at 0x7f87ec2935b0>
hi monkey