在 Python 中的文件二中获取文件一(有两个 类 和函数)元素

Getting File one (have two classes and functions) elements in file two in Python

我有一个文件 (PatchFinder.py) 有两个 classes:

class PatchFinder():
    
  def __init__(self, dataset, pf: float):
        #super(TopFeatures, self).__init__()
        self.pf = pf
        self.dataset = dataset
        self.datas = dataset[0].to('cpu')

    def TopFeaturesFind(self, g: Graph) -> Graph:
        Zxx, self.edge_index_, edge_weights = g.unfold()
        print(self.pf)
        print(Zxx)
        print(self.edge_index_)
        print(edge_weights)
        return Zxx
    def anotherMethod(self):
        print("something")

第 2 class

 class Class2(torch.nn.Module):
    def __init__(self, dataset, hidden_channels):
        super(GCN, self).__init__()

    def forward(self, x, edge_index_):
        return x

现在在另一个 File2.py 中,我想获得 TopFeaturesFind() 值。这就是我正在做的事情:

import PatchFinder
def main():
    tf = PatchFinder()
    t=tf.TopFeaturesFind()
    print(t)
if __name__ == '__main__':
    main()

但我收到错误消息:

    tf = PatchFinder()
TypeError: 'module' object is not callable

我这里做错了什么?我来自 java 背景。这对我来说似乎没问题。据我所知

如前所述:Python 中不存在只能从对象内部访问的“私有”实例变量。 source

注意:我不想继承 PatchFinder,两个文件都在同一个文件夹中。

您的 import PatchFinder 导入 模块 ,因此当您调用 PatchFinder() 时,您正在尝试“初始化”模块,而不是 class.这里有指导:https://docs.python.org/3/tutorial/modules.html

您需要做的就是指定要初始化模块中定义的对象。将 tf = PatchFinder() 更改为 tf = PatchFinder.PatchFinder(),它应该可以工作。

PatchFinder 是您正在调用的模块。访问 PatchFinder class 使用

tf = PatchFinder.PatchFinder()

或像这样导入 class

from PatchFinder import PatchFinder