Adding a Method to an Existing Object Instance

后端 未结 16 2963
夕颜
夕颜 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:15

    If it can be of any help, I recently released a Python library named Gorilla to make the process of monkey patching more convenient.

    Using a function needle() to patch a module named guineapig goes as follows:

    import gorilla
    import guineapig
    @gorilla.patch(guineapig)
    def needle():
        print("awesome")
    

    But it also takes care of more interesting use cases as shown in the FAQ from the documentation.

    The code is available on GitHub.

提交回复
热议问题