Python add to a function dynamically

前端 未结 7 1417
星月不相逢
星月不相逢 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

    If your class A inherits from object, you could do something like:

    def test2():
        print "test"
    
    class A(object):
        def test(self):
            setattr(self, "test2", test2)
            print self.test2
            self.test2()
    
    def main():
        a = A()
        a.test()
    
    if __name__ == '__main__':
        main()
    

    This code has no interest and you can't use self in your new method you added. I just found this code fun, but I will never use this. I don't like to dynamicaly change the object itself.

    It's the fastest way, and more understandable.

提交回复
热议问题