【问题标题】:Is there any way to access variable in one function of a file to another file有什么方法可以将文件的一个函数中的变量访问到另一个文件
【发布时间】:2020-02-18 09:03:41
【问题描述】:

我有 2 个文件 prgm.py 和 test.py

1.prgm.py

def move(self)
    H=newtest.myfunction()
    i= H.index(z)
    user=newuser.my_function() 
    print(user[i])

我将如何在名为 test.py 的其他代码中获取 user[i]

【问题讨论】:

  • 您的代码不清楚,但基本上您应该导入 prgm 并调用 prgm.your_val 或 prgm.your_fun()

标签: python function import call python-3.5


【解决方案1】:

您可以简单地返回结果,而不是打印结果。在第二个文件中,您只需从该源文件中导入函数并调用它。

鉴于这种情况,move实际上是一个类方法,所以你需要导入整个类并在第二个文件中实例化它

prgm.py

class Example:
   def move(self):
       H = newtest.myfunction() 
       i = H.index(z)
       user = newuser.my_function()
       return user[i]

test.py

from prgm import Example

example = Example()
user = example.move()
# do things with user

【讨论】:

    【解决方案2】:

    在另一个文件中使用 import 语句;

    像这样 - from prgm import move
    注意:为此,这两个文件需要在同一个文件夹中,或者您要导入的文件的路径需要在您的 PYTHONPATH 中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      • 2021-11-13
      • 2014-09-20
      • 1970-01-01
      相关资源
      最近更新 更多