问题
From my main code, I want to call a function X regardless of argument v. In the background, the function Y or Z is called based on the value of v.
For example, main code is -
i = X(v)
Now, functions Y or Z are called if v="a" or v="b".
def X(v):
pass
def Y(v):
# called if v="a"
def Z(v):
# called if v="b"
I think a decorator can be used but I don't have enough knowledge about decorators.
回答1:
The easiest way is to have X
call Y
or Z
. X
would then be more of a dispatcher instead of a decorator, which matches what you have (calling X
directly). Check out @ezig's answer for the code.
decorator
s are for changing something about a function, or its environment, or to register it -- not usually to pick different functions; although a notable exception to that is singledispatch, introduced into Python3.4.
An example of singledispatch (using an older version called simplegeneric) in my own code:
@simplegeneric
def float(*args, **kwds):
return __builtin__.float(*args, **kwds)
@float.register(timedelta)
def timedelta_as_float(td):
seconds = td.seconds
hours = seconds // 3600
seconds = (seconds - hours * 3600) * (1.0 / 3600)
return td.days * 24 + hours + seconds
@float.register(Time)
def Time_as_float(t):
return t.tofloat()
and then I can call float()
on timedelta
s, custom Time
s, or the normal stuff, and get a float back.
回答2:
Is there anything wrong with an if
statement?
def X(v):
if v == "a":
Y(v)
elif v == "b":
Z(v)
来源:https://stackoverflow.com/questions/31777424/python-calling-a-function-based-on-a-argument-value