nargout in Python

前端 未结 5 1125
甜味超标
甜味超标 2020-12-06 16:21

Does Python have any equivalent of nargout in MATLAB? I find nargout a very neat approach if we want to keep the number of return parameters flexible. Is there a way I can f

5条回答
  •  庸人自扰
    2020-12-06 16:23

    The function can't know what is going to be done with the return value, so it can't know how many are needed. What you could do is pass nargout as an argument to your function and use that to decide what to return:

    def f(a, nargout=1):
        if nargout == 1:
            return "one value"
        elif nargout == 2:
            return "two", "values"
        else:
            raise ValueError, "Invalid nargout!"
    

    This is an example of "explicit is better than implicit" as a Python philosophy. If you want two arguments out, you have to say explicitly that you want two arguments out. Implicitly deciding based on looking into the future to see what is going to be done with the result is discouraged in Python. It's perfectly possible to do a = f(x) and want to get a two-element tuple in a.

    For examples like yours, there are lots of better ways. One is to just do mean, std = a.mean(), a.std(), or more generally x, y = someFunc(a), otherFunc(a). If this particular combination of values is commonly needed, and there is some expensive computation shared by both operations that you don't want to duplicate, make a third function that clearly returns both and do x, y = funcThatReturnsTwoThings(a). All of these are explicit ways of keeping functions separate if they do different things.

提交回复
热议问题