Python: Passing a function name as an argument in a function -
I am trying to pass the function name to another function in the form of argument, but I get an error : "TypeError: 'Str' object is not worth calling" Here is a simple example of the problem:
def doIt (a, func, y, z): result = z result = func Return dork1 (arg1, arg2, arg3): thing = (arg1 + arg2) / arg3 return talk def dork2 (arg1, arg2, arg3): object = arg1 + (arg2 / arg3) return Talk about
when I call this:
Var = 'dork1' ned = doIt (3, var, 4, 9) print (ned)
I am getting:
traceback ( Most recent call final): File "& lt; pyshell # 9", line 1, & lt; Module & gt; (A, Y, Result) Type: Error: 'str' is not worth the object corner
If you want to pass name to the function, as you said and you are doing, of course you can not call it - why a" Will call a name "? It's meaningless.
If you want to call it, then pass the function yourself, which is the most powerful no
var = 'dork1' / Code> but without the quote
var = dork1
edit : O.P. in a comment How to obtain the miracle (!) Function object function name (in the form of a string) With this, it was shown to me that in a tutorial taught in OSCON (which I am just refunding) - get slides and pages 47 See, "Lazy-loading callback":
class LazyCallable (object): def __init __ (self, name): self.n, self.f = name, any def __call __ (Self, * a, ** k): if self.f none: modn, Funcn = self.n.rsplit ('.', 1) if not in modn sys.modules: __impo Rt___ (modn) self.f = getattr (sys.modules [modn], funcn) self.f (* a, * * k)
then you is usable ('somemodule .dork1 ')
and can stay happily any time later. If you do not have to deal with the modules of the course (which is a strange architecture that should be meant! -) It is easy to adjust this code.
Comments
Post a Comment