【问题标题】:How can i import updated variable with the value from another file in python如何使用 python 中另一个文件的值导入更新的变量
【发布时间】:2021-07-05 06:50:05
【问题描述】:

test.py

asd = ''

def upd():
    asd = 'Anything'

def hello():
    upd()
    print('hello')
    return asd

script.py

import test as tt

print(tt.hello())

如何在 script.py 中获取更新的 'asd' 值? 有人请建议

【问题讨论】:

  • 没有更新asd; test.asd 是一个完全不同于 upd 函数定义的 local 变量 asd 的变量。

标签: python python-3.x variables import


【解决方案1】:

试试这个

在 test.py 中

asd = ''
def upd():
    return 'Anything'
def hello():
    asd=upd()
    print('hello')
    return asd

在 script.py 中

import test as tt
asd=tt.hello()
print(asd)

【讨论】:

    【解决方案2】:

    你没有更新任何东西。 upd 创建了一个新的局部变量,该变量在调用返回后被丢弃。

    如果您的意思是让upd 更新全局 变量asd,则需要先将名称声明为全局。

    asd = ''
    
    def upd():
        global asd
        asd = 'Anything'
    
    def hello():
        upd()
        print('hello')
    

    现在,在调用tt.hello 之后,您可以像访问任何其他模块属性一样访问tt.asd

    import test as tt
    tt.hello()
    print(tt.asd)
    

    (我故意忽略了一个函数是否应该改变全局变量asd的问题。这样做有合理的用例,但问题中没有足够的上下文在这种情况下做出任何此类判断。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-17
      • 2019-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      相关资源
      最近更新 更多