Is there a way in Python to return a value via an output parameter?

后端 未结 5 1796
耶瑟儿~
耶瑟儿~ 2020-12-10 00:50

Some languages have the feature to return values using parameters also like C#. Let’s take a look at an example:

class OutClass
{
    static void OutMethod(o         


        
5条回答
  •  误落风尘
    2020-12-10 01:13

    You can do that with mutable objects, but in most cases it does not make sense because you can return multiple values (or a dictionary if you want to change a function's return value without breaking existing calls to it).

    I can only think of one case where you might need it - that is threading, or more exactly, passing a value between threads.

    def outer():
        class ReturnValue:
            val = None
        ret = ReturnValue()
        def t():
            # ret = 5 won't work obviously because that will set
            # the local name "ret" in the "t" function. But you
            # can change the attributes of "ret":
            ret.val = 5
    
        threading.Thread(target = t).start()
    
        # Later, you can get the return value out of "ret.val" in the outer function
    

提交回复
热议问题