【问题标题】:How to get the data from function inside one file to another file如何从一个文件中的函数获取数据到另一个文件
【发布时间】:2018-11-13 08:29:49
【问题描述】:

我必须将一些值从一个文件导入到另一个文件。我在 second.py 中有一个函数名 myFunc,其中我有一个变量名“a”。现在我想在 main 函数内的 first.py 文件中显示这个值。

first.py
-------
import os
import second.py import *

def main():
    //here i need to print from another file


if __name__ == '__main__':
    main()

second.py
---------
import os

def myFunc(var1, var2):
    a = 'test user'

【问题讨论】:

  • 可以在second.py中创建一个类,然后声明变量a。然后在 first.py 中,您可以为该类创建一个对象,并且应该能够访问该变量。
  • @San 你能举个例子吗
  • 你不能真正从这样的函数内部拉出一个变量(即使是在单个文件的情况下)。如果myFunc 返回 a,你可以在first.py中写:print(myFunc(..., ...)),由于myFunc返回a,它会在你运行first.py时打印出来。

标签: python python-2.7 import python-import python-module


【解决方案1】:

尝试在 second.py 中返回 a

import os

def myFunc(var1, var2):
    a = 'test user'
    return a

然后在 first.py 中尝试下面的代码

import os
import second

def main():
    print(second.myFunc(something,something))


if __name__ == '__main__':
    main()

注意:你应该填写参数的地方(意思是var1var2

【讨论】:

    【解决方案2】:

    以下是我在 cmets 中建议的示例。

    first.py

    import os
    from second import first_class
    
    def main():
        obj = first_class()
        print(obj.a)
    
    
    if __name__ == '__main__':
        main()
    

    second.py

    import os
    
    class first_class:
        def __init__(self):
            self.a = 'test user'
    

    希望对你有帮助!!

    【讨论】:

    • 我得到 obj = first_class() NameError: global name 'first_class' is not defined
    • @user1687891 抱歉,我错过了在类定义中保留括号,请检查更新后的代码。
    • 是的,我在我的代码中使用了括号,但它说同样的错误。
    • @Dux 感谢您的编辑 Bud !!。不要知道我在写那个 import 语句时在想什么。
    • @user1687891 请查看更新后的导入声明。它现在应该可以工作了。
    【解决方案3】:

    当您定义一个函数时,其中的变量在全局范围之外,因此它们只能在该函数内访问,如果您想获取该函数的值,则返回它,您的问题的解决方案可能如下

    second.py

    import os
    def myFunc(var1, var2):
        a = 'test user';
        return a
    

    【讨论】:

      猜你喜欢
      • 2020-09-25
      • 2018-06-21
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      相关资源
      最近更新 更多