程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python monkey patch

編輯:Python

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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved