【问题标题】:want to use the variable in this file not in the import one想使用这个文件中的变量而不是导入的变量
【发布时间】:2021-09-08 06:34:10
【问题描述】:

大家好,这是我在项目中遇到的问题。这里我用一个简单的例子来解释一下。当我尝试运行 main.py 时,我想使用此模块中的变量而不是助手中的变量,但即使我删除了全局变量“a”,输出结果也始终为 2。 不输入函数参数有什么办法吗?希望有人能帮忙:(

helper.py

a = 2
def test():
   print(a)

ma​​in.py

from helper import *

del globals()["a"]
if __init__ == "__main__":
    a = 10
    test()

【问题讨论】:

    标签: python import global-variables


    【解决方案1】:

    你可以修改属性:

    ma​​in.py

    import helper
    
    if __name__ == "__main__":
        helper.a = 10
        helper.test()
    

    输出:

    10
    

    编辑:

    你可以试试:

    helper.py

    a = [2]
    def test():
       print(a[0])
    

    ma​​in.py

    from helper import *
    
    if __name__ == "__main__":
        a.clear()
        a.append(10)
        test()
    

    输出:

    10
    

    【讨论】:

    • 有没有不传参数的方法
    • @YanJimmy 编辑了我的答案看看,如果有帮助记得怎么做
    • 感谢您的回复!另一个问题。因为在我的项目中有很多我想使用的函数和变量,这就是我从 helper import * 编写的原因。我的问题是如果我只想修改一些全局变量,我还可以使用 from helper import * 吗?
    • @YanJimmy 两者都可以,import helper 也可以,from helper import * 也可以,如果有帮助记得点赞:P
    • @YanJimmy 我的解决方案是唯一可行的方法
    猜你喜欢
    • 2011-01-04
    • 2013-11-25
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    相关资源
    最近更新 更多