python - How to pass an instance method, that uses instance variables, as argument to another function? -
i want pass method foo of instance of class a function run_function. method foo use instance variables of class a.
here minimal example, in instance variable of a self.a_var, , foo prints variable.
class a: def __init__(self,a_var): self.a_var=a_var def foo(self): print(self.a_var) class b: def __init__(self, a): self.a=a # edit (comment compile) self.a.do_something() def run_function(self): self.a.foo() def run_function_2(self, bar): bar() mya = a(42) mya.foo() # current implementation myb=b(mya) myb.run_function() # better(?) implementation myb.run_function_2(mya.foo) at moment pass instance mya of class a instance of b , explicitly call self.a.foo(). forces name of function of ato foo. stupid.
the better (?) implementation passes function of instance run_function2. works, not sure if "safe".
question:
are there loopholes don't see @ moment?
the important part is, method foo, passed, needs access instance variables of (its) class instance. so, foo called inside run_function_2 have access instance variables of mya?
is there better way implement this?
edit: forgot add, class b have instance of a, since has do_something instance. maybe change something(?). sorry!
for second implementation, have considered following:
>>> myaa = a(42) >>> myab = a(43) >>> myb = b(myab) >>> myb.run_function_2(myaa.foo) 42 this might not want. how using getattr() , passing in desired method name:
>>> class c: ... def __init__(self, a): ... self.a = ... def run_fct(self, bar): ... fct = getattr(self.a, bar) ... fct() ... >>> myc = c(myaa) >>> myc.run_fct('foo') 42
Comments
Post a Comment