Adding a Method to an Existing Object Instance

后端 未结 16 2966
夕颜
夕颜 2020-11-21 05:45

I\'ve read that it is possible to add a method to an existing object (i.e., not in the class definition) in Python.

I understand that it\'s not always good to do so

16条回答
  •  礼貌的吻别
    2020-11-21 06:02

    In Python monkeypatching generally works by overwriting a class or function's signature with your own. Below is an example from the Zope Wiki:

    from SomeOtherProduct.SomeModule import SomeClass
    def speak(self):
       return "ook ook eee eee eee!"
    SomeClass.speak = speak
    

    This code will overwrite/create a method called peak in the class. In Jeff Atwood's recent post on monkey patching, he showed an example in C# 3.0 which is the current language I use for work.

提交回复
热议问题