我坚持使用另一个函数中前一个函数中定义的变量。例如,我有这段代码:
def get_two_nums():
...
...
op = ...
num1 = ...
num2 = ...
answer = ...
def question():
response = int(input("What is {} {} {}? ".format(num1, op, num2)))
if response == answer:
.....
我如何使用第二个函数中第一个函数中定义的变量?提前谢谢
答案 0 :(得分:4)
变量是函数的局部变量;您需要return
要与调用者共享的相关值,并将它们传递给使用它们的下一个函数。像这样:
def get_two_nums():
...
# define the relevant variables
return op, n1, n2, ans
def question(op, num1, num2, answer):
...
# do something with the variables
现在你可以打电话了
question(*get_two_nums()) # unpack the tuple into the function parameters
或
op, n1, n2, ans = get_two_nums()
question(op, n1, n2, ans)
答案 1 :(得分:3)
为什么不返回一个元组?
public class CompleteService
{
public Service Service { get; set; }
public List<XrefSubMenuToServices> Xrefs { get; set; }
public CompleteService()
{
this.Service = new Service();
this.Xrefs = new List<XrefSubMenuToServices>();
}
public CompleteService(Service service, List<XrefSubMenuToServices> xrefs)
{
this.Service = service;
this.Xrefs = xrefs;
}
}
答案 2 :(得分:2)
您不能简单地传递它们,因为get_two_nums
中的变量仅在get_two_nums
函数的范围内定义。
所以基本上你有两个选择:
将其值作为元组返回到 @TimPietzcker 和 @ Tgsmith61591 提议的另一个函数的范围内。
将get_two_nums
函数中的变量定义为全局变量(有关详情,请参阅global statement),如下面的代码片段所述:
def get_two_nums():
global num1
num1 = 'value1'
global num2
num2 = 'value2'
global num3
num3 = 'value3'
def question():
# Call get_two_nums to set global variables for further using
get_two_nums()
response = int(input("What is {} {} {}? ".format(num1, num2, num3)))
if response == answer:
# Some code here ...
警告:应避免使用全局变量,请参阅Why are global variables evil?以更好地了解我所说的内容......