为什么不能从同一目录中的类导入函数?

问题描述 投票:0回答:3

在我的builder / graph_builder.py中,我有一个课

class GraphBuilder(object):

  def __init__(self):
    pass

  @staticmethod
  def parse(path):
     ...
     return path

然后在同一目录中,我有一个linker.py,并且我想导入'parse'函数:

 from builder.graph_builder.GraphBuilder import parse

我在PyCharm中,它提示“来自builder.graph_builder。”是可见的,但是在此之后,它不能引用GraphBuilder和parse函数。

为什么?

python pycharm
3个回答
3
投票

语法为from MODULE import NAME,因此

from builder.graph_builder import GraphBuilder

可以,但是

from builder.graph_builder.GraphBuilder import parse

不会-builder.graph_builder.GraphBuildernot一个模块。


1
投票

由于graph_builder位于同一目录中,因此您可以直接引用graph_builder。

此外,GraphBuilder是一个类,因此您可以实例化解析函数并将其存储到变量中

您可以尝试这样:

from graph_builder import GraphBuilder


if __name__=='__main__':
    path="C:\\Users\\"
    parse=GraphBuilder().parse
    test=parse(path)

0
投票

无法从python中的类导入方法

您必须先导入类,然后再调用方法。即使它是静态方法,也会发生。

© www.soinside.com 2019 - 2024. All rights reserved.