Adding a Method to an Existing Object Instance

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

    from types import MethodType
    
    def method(self):
       print 'hi!'
    
    
    setattr( targetObj, method.__name__, MethodType(method, targetObj, type(method)) )
    

    With this, you can use the self pointer

提交回复
热议问题