Python add to a function dynamically

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

    There are a lot of really good suggestions above, but one I didn't see was passing in a function with the call. Might look something like this:

    class A(object):
        def test(self, deep=lambda self: self):
            print "here"
            deep(self)
    def test2(self):
        print "and here"
    

    Using this:

    >>> a = A()
    >>> a.test()
    here
    >>> a.test(test2)
    here
    and here
    
    0 讨论(0)
提交回复
热议问题