【问题标题】:How to call the functions present in one .py file from other .py file?如何从另一个 .py 文件调用一个 .py 文件中存在的函数?
【发布时间】:2016-12-21 21:55:27
【问题描述】:

我有两个文件,我想从另一个文件中导入一个类。

文件one.py

class One: 
    def printNumber( self, a ):
        print (a)

和文件two.py:

#import One # gives error no module named One
#import one # gives error no module named one

class Two:
  # Here I want to call printNumber method from one.py

【问题讨论】:

  • 你试过谷歌搜索,“如何在 Python 中导入”?
  • 如果这是python 2,根据语法判断,您可能需要在同一目录中有一个名为'init.py'的文件(无法获取下划线语法....)
  • Python import mechanics的可能重复

标签: python python-3.x import


【解决方案1】:

将文件保存在同一目录中,然后使用类似于以下格式的内容。

from one import One

one = One()

class Two:
    a = 5
    one.printNumber(a)

编辑:在 Pycharm 中工作时,您需要标记源根目录以导入您自己的文件。

【讨论】:

  • 使用 from 也会出现同样的错误。两个文件都在同一个目录中。我正在使用 pycharm IDE
  • 更新了我使用 Pycharm 的答案。
  • 感谢您的帮助
  • @Sumith - 如果它解决了您的问题,请接受此答案。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-18
  • 1970-01-01
  • 2012-10-10
  • 1970-01-01
相关资源
最近更新 更多