Functor call in Python

It should be easy, but somehow I don’t understand this. I want to apply this function. A background is copying a class and applying this method to a newly created copy.

The main change. Sorry for that.

import copy class A: def foo(self,funcName): print 'foo' funcName() def Bar(self): print 'Bar' def copyApply(self,funcName): cpy = copy.copy() # apply funcName to cpy?? a = A() func = a.Bar() a.foo(func) # output 'Bar' b = a.copyApply(foo) # new copy with applied foo 
+4
source share
2 answers

Please note that your A.foo does not use the name of the function, but the function itself.

 class A: def bar(self): print 'Bar' def apply(self, func): func() # call it like any other function def copyApply(self, func): cpy = copy.copy(self) func(cpy) # cpy becomes the self parameter a = A() func = a.bar # don't call the function yet a.apply(func) # call the bound method `a.bar` a.apply(a.bar) # same as the line above a.copyApply(A.bar) # call the unbound method `A.bar` on a new `A` 

In python, a.foo() same as A.foo(a) , where a is of type a . Therefore, your copyApply method accepts the unbound bar method as an argument, while foo accepts the associated method.

+4
source

If you want to call a method on a copy of an instance

 class A (object): def foo(self): pass def copyApply(self,func): cpy = copy.copy(self) func(cpy) 

and name it like that

 a = A() a.copyApply(A.foo) 

note I get the foo method from the class, not from the instance, since A.foo expects instance A as the first argument, and A.foo takes no arguments.

+1
source

Source: https://habr.com/ru/post/1442543/


All Articles