【问题标题】:Passing variables between functions: recall returned variables or use classes?在函数之间传递变量:调用返回的变量还是使用类?
【发布时间】:2019-04-05 19:38:07
【问题描述】:

我找到了一种在函数之间传递变量的简单方法。

但是,我很想知道另一种方法是否更简单,例如创建一个类。或者,事实上,如果我传递变量的方法有问题。

我最近一直在努力理解如何在函数之间传递变量。

关于这个问题,有几个 StackOverflow 问题供新手参考(请参阅 hereherehere)。然而,许多答案往往过于针对提问者提供的代码 sn-p。

我想了解一般工作流程。也就是说,如何将变量A传递给函数A,进行操作,然后传递给函数B,再次更改,然后在函数C中输出,例如。

我想我有一个解决办法:

def main():
    output()

def function1():
    sentence = ("This is short.")   # here is a string variable
    value = (10)                    # here is a number variable
    return sentence, value          # they are returned

def firstAddition():
    sentence, value = function1()   # variables recalled by running function1()
    add1stSentence = "{}at is longer.".format(sentence[0:2]) # string changed
    add1stValue = 2 * value                                  # number changed
    return add1stSentence, add1stValue    # the changed values are returned

def secondAddition():               # This function changes variables further
    add1stSentence, add1stValue = firstAddition()
    add2ndSentence = "{} This is even longer.".format(add1stSentence)
    add2ndValue = 2 * add1stValue
    return add2ndSentence, add2ndValue

def output():                       # function recalls all variables and prints
    sentence, value = function()
    add1stSentence, add1stValue = firstAddition()
    add2ndSentence, add2ndValue = secondAddition()
    print(sentence)
    print(str(value))
    print(add1stSentence)
    print(str(add1stValue))
    print(add2ndSentence)
    print(str(add2ndValue))

以上代码的输出如下:

这很短。 10 那更长。 20 那更长。这甚至更长。 40

函数之间传递原句和值变量。

我的变量传递方式有四个步骤:

  1. 构建操作变量的函数A;
  2. 在函数A结束时返回那些变量;
  3. 在函数B开始时,调用每个变量,which = functionA;
  4. functionB 操作变量并再次返回它们以进行进一步操作,或输出变量。

我的问题是:

(a) 我的方式是公认的做法吗?

(b) 有没有更好或更优雅的方法在函数之间传递变量?

【问题讨论】:

  • 将值作为参数传递有什么问题?
  • 显式比隐式好得多。您隐藏使用此方法传递的所有数据,这使您的代码更难理解。此外,您通过硬编码每个函数中的数据源来消除所有灵活性。简而言之:使用参数。 :)
  • @DYZ 干杯。我刚刚发现这个介绍了他们。 stackoverflow.com/questions/919680/…
  • @ThierryLathuille 好的。使用参数似乎是共识。下方回复的 Nick Vitha 也在告诉我同样的事情。

标签: python-3.x


【解决方案1】:

将变量传递给函数的方式是通过函数arguments(也称为函数parameters)。

在您的情况下,您可以修改 functionB 以接受输入。您的示例有点复杂,但我将其简化为便于您理解。

现在,你基本上是在做这样的事情:

def functionA():
    return 12

def functionB():
    return 5

def caller():
    holder = functionA() + functionB()
    print(holder)

一般来说,这工作,但它更喜欢做这样的事情:

def functionA():
   return 5

def functionB(number):
   return(number+5)

def caller():
   holder = functionA()
   output = functionB(holder)
   print(output)

甚至:

def caller():
   print(functionB(functionA()))

您可以将函数的输出传递给其他函数。

在继续更复杂的事情之前,我会阅读更多关于 python 函数 https://www.tutorialspoint.com/python3/python_functions.htm 的内容。

【讨论】:

  • 非常感谢,尼克。非常感谢您的快速回复。
猜你喜欢
  • 2019-11-12
  • 1970-01-01
  • 1970-01-01
  • 2020-07-02
  • 1970-01-01
  • 2018-07-29
  • 2015-04-03
  • 2013-04-09
  • 2013-03-07
相关资源
最近更新 更多