【问题标题】:How to assign a variable within a function to be referenced in later in code?如何在函数中分配一个变量,以便稍后在代码中引用?
【发布时间】:2021-02-14 14:21:46
【问题描述】:

我在从另一个文件调用函数以在当前文件中设置变量时遇到问题,正在寻求帮助。

这行得通:

def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x)

正确打印“Python 很棒”

这不起作用:

文件1.py

def myfunc():
  global x
  x = "fantastic"

file2.py

from up2levels.up1level.file1 import * 

myfunc()

print("Python is " + x)

结果:'x 未定义'。 我希望这个结果是 'Python is Fantastic'

我在这里缺少什么?感谢您的帮助!

编辑:我已经尝试了一些答案,但仍然遇到问题,它们在非常愚蠢的示例中工作,但是我无法让它与我的代码一起工作。这就是我正在尝试做的事情:遍历数据框以查找某些参数以显示(for循环)。满足参数后,将一行数据框传入函数(File1.py),返回5-6个不同的变量,并记录在File2.py中。

【问题讨论】:

  • 这能回答你的问题吗? Global Variables between different modules
  • x 是一个全局变量file1 模块中。您需要在 file2.py 中使用file1.x
  • 这样使用全局变量并不有趣。你可以直接返回x...

标签: python function variables variable-assignment


【解决方案1】:

文件1.py

def myfunc():
    x = "fantastic"
    return x

文件2.py

import File1 

print("Python is " + File1.myfunc())

【讨论】:

    【解决方案2】:
    函数中的
    x = 'fantastic'
    在本地设置变量。

    使用globals() 全局设置变量。

    def myfunc():
        globals()['x'] = '太棒了'
    
    我的函数()
    
    print("Python 是" + x)

    希望对你有用。

    【讨论】:

    • 如果他想添加变量不返回等方式,可以。
    猜你喜欢
    • 1970-01-01
    • 2018-02-18
    • 2020-05-18
    • 2013-09-30
    • 2017-08-04
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多