首頁  >  文章  >  後端開發  >  解釋Python中的monkey patching是什麼意思?

解釋Python中的monkey patching是什麼意思?

PHPz
PHPz轉載
2023-08-19 11:53:16868瀏覽

解释Python中的monkey patching是什么意思?

Monkey patching is the technique of dynamic modification of a piece of code at the run time. Actually by doing monkey patch we change the behavior of code but without affecting the originalsource .

歷史

Monkey patch(猴子補丁)一詞源自於遊擊補丁(guerrilla patch),guerrilla幾乎意味著大猩猩,可以定義猴子物種。遊擊補丁指的是秘密地進行變更。但是猴子補丁聽起來更容易發音,所以現在被稱為“Monkey patch”。在「Monkey-patch」一詞中,monkey定義了dynamic(動態)這個字。

Monkey patching in python

Monkey patching in python refers to modifying or updating a piece of code or class or any module at the runtime. In simple words, we can change the behavior or working of a class/ module at the runtime at sooo . But sometimes monkey patching is considered bad practice because the definition of object does not accurately describe how the object is behaving in the code.

Example

class first:
   def print(self)
      print(“hello world”)

輸出

If we run the above code it will generate the following output −

Hello world

代碼猴子補丁後

Example

Import monkey
def monkey_function(self):
   print(“Hello world”)
# updating the print() with monkey_function()
monkey.A.print = monkey_function

# revoking method print() as method monkey_function()
obj = monkey.A()
obj print()

輸出

If we run the above code it will generate the following output −

Hello world

以上是解釋Python中的monkey patching是什麼意思?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除