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

PHPz
發布: 2023-08-19 11:53:16
轉載
873 人瀏覽過

解释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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板