python - Adding lines to a function -
suppose had 2 functions within function so:
def foobar(istheworldround = true): def foo(): print("hi, i'm foo.") def bar(): print("hi, i'm bar.") thefunction = none if (istheworldround): return bar else: return [bar, foo]
so, can this:
myfunction = foobar(false) myfunction() >>> hi, i'm bar >>> hi, i'm foo
concerning example have 2 questions:
- what proper way perform commented line?
- is there way can without explicitly defining
foo
?
putting 2 functions list gives that; list of functions. does not make new function calls both of previous functions. that, need define new wrapper function, e.g.:
def call_all(*funcs): """create new wrapper call each function in turn.""" def wrapper(*args, **kwargs): """call functions , return list of outputs.""" return [func(*args, **kwargs) func in funcs] return wrapper
(if *
syntax unfamiliar, see what ** (double star) , * (star) parameters?), can use like:
thefunction = call_all(bar, foo)
note that:
thefunction = none if (istheworldround): return bar else: return [bar, foo]
is bit awkward, write as:
if istheworldround: return bar return [bar, foo]
you should rename functions/variables per the style guide.
Comments
Post a Comment