Python: Calling a function based on a argument value

一个人想着一个人 提交于 2021-01-28 08:45:47

问题


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.

decorators 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 timedeltas, custom Times, 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!