Python add to a function dynamically

前端 未结 7 1407
星月不相逢
星月不相逢 2020-12-08 04:53

how do i add code to an existing function, either before or after?

for example, i have a class:

 class A(object):
     def test(self):
         print         


        
7条回答
  •  春和景丽
    2020-12-08 05:41

    Copy and paste, enjoy!!!!!

    #!/usr/bin/env python 
    
    def say(host, msg): 
       print '%s says %s' % (host.name, msg) 
    
    def funcToMethod(func, clas, method_name=None): 
       setattr(clas, method_name or func.__name__, func) 
    
    class transplant: 
       def __init__(self, method, host, method_name=None): 
          self.host = host 
          self.method = method 
          setattr(host, method_name or method.__name__, self) 
    
       def __call__(self, *args, **kwargs): 
          nargs = [self.host] 
          nargs.extend(args) 
          return apply(self.method, nargs, kwargs) 
    
    class Patient: 
       def __init__(self, name): 
          self.name = name 
    
    if __name__ == '__main__': 
       jimmy = Patient('Jimmy') 
       transplant(say, jimmy, 'say1') 
       funcToMethod(say, jimmy, 'say2') 
    
       jimmy.say1('Hello') 
       jimmy.say2(jimmy, 'Good Bye!') 
    

提交回复
热议问题