Adding a Method to an Existing Object Instance

后端 未结 16 3017
夕颜
夕颜 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条回答
  •  旧时难觅i
    2020-11-21 06:11

    This is actually an addon to the answer of "Jason Pratt"

    Although Jasons answer works, it does only work if one wants to add a function to a class. It did not work for me when I tried to reload an already existing method from the .py source code file.

    It took me for ages to find a workaround, but the trick seems simple... 1.st import the code from the source code file 2.nd force a reload 3.rd use types.FunctionType(...) to convert the imported and bound method to a function you can also pass on the current global variables, as the reloaded method would be in a different namespace 4.th now you can continue as suggested by "Jason Pratt" using the types.MethodType(...)

    Example:

    # this class resides inside ReloadCodeDemo.py
    class A:
        def bar( self ):
            print "bar1"
            
        def reloadCode(self, methodName):
            ''' use this function to reload any function of class A'''
            import types
            import ReloadCodeDemo as ReloadMod # import the code as module
            reload (ReloadMod) # force a reload of the module
            myM = getattr(ReloadMod.A,methodName) #get reloaded Method
            myTempFunc = types.FunctionType(# convert the method to a simple function
                                    myM.im_func.func_code, #the methods code
                                    globals(), # globals to use
                                    argdefs=myM.im_func.func_defaults # default values for variables if any
                                    ) 
            myNewM = types.MethodType(myTempFunc,self,self.__class__) #convert the function to a method
            setattr(self,methodName,myNewM) # add the method to the function
    
    if __name__ == '__main__':
        a = A()
        a.bar()
        # now change your code and save the file
        a.reloadCode('bar') # reloads the file
        a.bar() # now executes the reloaded code
    

提交回复
热议问题