I am trying to add class members to a class based on another, and I'm running into some issues with the loop. All of the functions assigned wind up calling the last function found.
import inspect
from pprint import pp
from functools import wraps
def action(f):
f.action = True
return f
class x1:
@action
def func1(self):
return 1
def func2(self):
return 2
@action
def func3(self):
return 3
class x2:
pass
funcs = inspect.getmembers(x1, predicate=inspect.isfunction)
for fn, f in funcs:
if getattr(f, 'action', False):
@wraps(f)
def call(self):
print(fn)
return f(self)
setattr(x2, fn, call)
a = x2()
pp({
'funcs': [a.func1, a.func3],
'func1': a.func1(),
'func3': a.func3()
})
Output is:
func3
func3
{'funcs': [<bound method x1.func1 of <__main__.x2 object at 0x7f33eade1fd0>>,
<bound method x1.func3 of <__main__.x2 object at 0x7f33eade1fd0>>],
'func1': 3,
'func3': 3}
...when obviously func1
should return 1, not 3.