How to access a variable defined inside a function, from outside that function
我一直坚持在另一个函数中使用前一个函数中定义的变量。例如,我有以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 | def get_two_nums(): ... ... op = ... num1 = ... num2 = ... answer = ... def question(): response = int(input("What is {} {} {}?".format(num1, op, num2))) if response == answer: ..... |
如何在第二个函数中使用第一个函数中定义的变量?提前谢谢你
变量是函数的局部变量;您需要
1 2 3 4 5 6 7 8 | def get_two_nums(): ... # define the relevant variables return op, n1, n2, ans def question(op, num1, num2, answer): ... # do something with the variables |
现在你可以打电话了
1 | question(*get_two_nums()) # unpack the tuple into the function parameters |
或
1 2 | op, n1, n2, ans = get_two_nums() question(op, n1, n2, ans) |
为什么不返回一个元组?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | def get_two_nums(): ... ... op = ... num1 = ... num2 = ... answer = ... return op, num1, num2, answer def question(): op, num1, num2, answer = get_two_nums() response = int(input("What is {} {} {}?".format(num1, op, num2))) if response == answer: # the rest of your logic here |
不能简单地传递它们,因为
将它们的值作为元组返回到另一个函数的作用域中,如@timpietzcker和@tgsmith61591所建议的那样。
将
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 ... |
警告:应该避免使用全局变量,请参阅为什么全局变量是邪恶的?为了更好地了解我在说什么…