如何从函数外部访问函数内部定义的变量 [英] How to access a variable defined inside a function, from outside that function

查看:36
本文介绍了如何从函数外部访问函数内部定义的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直坚持在另一个函数中使用在前一个函数中定义的变量.例如,我有这个代码:

I am stuck on using variables defined in a previous function in another function. For example, I have this code:

def get_two_nums():
    ...
    ...
    op = ...
    num1 = ...
    num2 = ...
    answer = ...

def question():
    response = int(input("What is {} {} {}? ".format(num1, op, num2)))
    if response == answer:
        .....

我将如何在第二个函数中使用第一个函数中定义的变量?提前谢谢您

How will I use the variables defined in the first function in the second function? Thank you in advance

推荐答案

变量是函数的局部变量;您需要返回您想要共享给调用者的相关值,并将它们传递给使用它们的下一个函数.像这样:

Variables are local to the functions; you need to return the relevant values you want to share to the caller and pass them to the next function that uses them. Like this:

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)

这篇关于如何从函数外部访问函数内部定义的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆