【发布时间】:2019-04-05 19:38:07
【问题描述】:
我找到了一种在函数之间传递变量的简单方法。
但是,我很想知道另一种方法是否更简单,例如创建一个类。或者,事实上,如果我传递变量的方法有问题。
我最近一直在努力理解如何在函数之间传递变量。
关于这个问题,有几个 StackOverflow 问题供新手参考(请参阅 here、here 和 here)。然而,许多答案往往过于针对提问者提供的代码 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
函数之间传递原句和值变量。
我的变量传递方式有四个步骤:
- 构建操作变量的函数A;
- 在函数A结束时返回那些变量;
- 在函数B开始时,调用每个变量,which = functionA;
- functionB 操作变量并再次返回它们以进行进一步操作,或输出变量。
我的问题是:
(a) 我的方式是公认的做法吗?
(b) 有没有更好或更优雅的方法在函数之间传递变量?
【问题讨论】:
-
将值作为参数传递有什么问题?
-
显式比隐式好得多。您隐藏使用此方法传递的所有数据,这使您的代码更难理解。此外,您通过硬编码每个函数中的数据源来消除所有灵活性。简而言之:使用参数。 :)
-
@DYZ 干杯。我刚刚发现这个介绍了他们。 stackoverflow.com/questions/919680/…
-
@ThierryLathuille 好的。使用参数似乎是共识。下方回复的 Nick Vitha 也在告诉我同样的事情。
标签: python-3.x