【问题标题】:Is there a way in Python to return a value via an output parameter?Python中有没有办法通过输出参数返回一个值?
【发布时间】:2011-01-15 21:25:56
【问题描述】:

某些语言具有使用参数返回值的功能,例如 C#。 我们来看一个例子:

class OutClass
{
    static void OutMethod(out int age)
    {
        age = 26;
    }
    static void Main()
    {
        int value;
        OutMethod(out value);
        // value is now 26
    }
}

那么在 Python 中是否也有类似的东西可以使用参数获取值?

【问题讨论】:

  • 很难理解的问题。需要详细说明吗?
  • @tokland:我认为 OP 想要做的是通过引用而不是像 Python 通常那样通过值传递参数。
  • 您的意思是“输出”-“返回”吗?或者类似通过引用传递参数?

标签: python


【解决方案1】:

Python 可以返回一个包含多个项目的元组:

def func():
    return 1,2,3

a,b,c = func()

但你也可以传递一个可变参数,并通过对象的变异返回值:

def func(a):
    a.append(1)
    a.append(2)
    a.append(3)

L=[]
func(L)
print(L)   # [1,2,3]

【讨论】:

  • 是的,这是在 python 中处理多个返回值的方法。返回元组比尝试修改给定参数之一更好
  • 我不太确定在这里说“返回多个值”是否合适。它实际上返回一个值,即包含多个元素的tuple
  • 有原因。例如众所周知的“TryDo”模式:if try_parse(out result): print(result)。这段代码很干净。尝试在这里使用元组,它会变得丑陋。
  • 那不是有效的 Python。在 Python 中,result = parse(something) 会在出错时引发异常并包裹在 try/except 中。
  • “没有理由”有时意味着“我还没想到理由”。 @renadeen 很好,我实际上是来这里寻找 TryDo 模式的。 If-else 树将是编写多个解析尝试的更好方法。 Mark Tolonen,try/except 每次尝试都会嵌套更深,或者我还没有想到不会这样做的方法。
【解决方案2】:

你的意思是像通过引用传递?

对于 Python 对象,默认是通过引用传递。但是,我认为您不能更改 Python 中的引用(否则不会影响原始对象)。

例如:

def addToList(theList):   # yes, the caller's list can be appended
    theList.append(3)
    theList.append(4)

def addToNewList(theList):   # no, the caller's list cannot be reassigned
    theList = list()
    theList.append(5)
    theList.append(6)

myList = list()
myList.append(1)
myList.append(2)
addToList(myList)
print(myList)   # [1, 2, 3, 4]
addToNewList(myList)
print(myList)   # [1, 2, 3, 4]

【讨论】:

  • Python 不是引用调用。
【解决方案3】:

传递一个列表或类似的东西并将返回值放在那里。

【讨论】:

    【解决方案4】:

    另外,如果你喜欢阅读一些代码,我认为pywin32 有办法处理输出参数。

    在 Windows API 中,严重依赖输出参数是一种常见的做法,所以我认为他们必须以某种方式处理它。

    【讨论】:

      【解决方案5】:

      您可以使用可变对象执行此操作,但在大多数情况下它没有意义,因为您可以返回多个值(或者如果您想更改函数的返回值而不中断对它的现有调用,则可以返回字典)。

      我只能想到一种你可能需要它的情况——那就是线程,或者更准确地说,在线程之间传递一个值。

      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
      

      【讨论】:

      • QueueManager 更适合多线程或多处理。
      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2017-02-21
      • 2021-03-19
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      相关资源
      最近更新 更多