首页 > 解决方案 > 如何从一个文件中的函数获取数据到另一个文件

问题描述

我必须将一些值从一个文件导入另一个文件。我在 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'

标签: pythonpython-2.7importpython-importpython-module

解决方案


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

第一个.py

import os
from second import first_class

def main():
    obj = first_class()
    print(obj.a)


if __name__ == '__main__':
    main()

第二个.py

import os

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

希望能帮助到你 !!


推荐阅读