【问题标题】:How do I fix the Attribute Error that I get when trying to import a function from another .py file? [duplicate]如何修复尝试从另一个 .py 文件导入函数时出现的属性错误? [复制]
【发布时间】:2020-07-24 11:44:23
【问题描述】:

当从this github repo 运行inspect_model.ipynb 时,我正在尝试print 图像的联合交集 (IoU) 值。该函数位于另一个 python 文件 (model.py) 中。我已按照类似问题here 的答案中的步骤进行操作,但收到如下所示的错误消息。

两个文件的目录树是:

/Mask_RCNN-master (working directory)

               / model.py
               / inspect_model.ipynb

导入nbimporter 和包含函数的文件(model.py)

import nbimporter
import model

我要调用的函数代码:

#to print IoU of image
class Accuracy():
    def __init__(self):
        print("IoU: ",iou)

我用来调用我正在运行的笔记本中的函数的代码:

new = model.Accuracy()

错误信息:


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-58-383458c9727b> in <module>()
     20 print("mAP @ IoU=50: ", np.mean(APs))
     21 
---> 22 new = model.Accuracy()

AttributeError: 'MaskRCNN' object has no attribute 'Accuracy'

【问题讨论】:

  • 将 .py 文件导入 .ipynb 文件需要一些额外的步骤。 This 可能会有所帮助。
  • 该仓库中的model.py 文件没有名为Accuracy 的类。这个词只在line 285的评论中出现一次。
  • 看起来model 不是模块,而是使用model = MaskRCNN(...) 创建的,现在在MaskRCNN 中找不到Accuracy
  • @MattDMo Yupe 它没有。我已将该类添加到model.py 中,以便运行print("IoU: ", iou)。然后,我想在inspect_model.ipynb notebook 中调用它
  • @furas 那么,解决方案是运行 from model import Accuracy 吗?正如 Justin Iven Muller 在下面的答案中指出的那样。

标签: python python-3.x


【解决方案1】:

进口: from model import Accuracy

...而且类本身通常没有括号:

class Accuracy:
    def __init__(self):
        print("IoU: ",iou)

【讨论】:

  • 我试过了...我仍然收到AttributeError: 'MaskRCNN' object has no attribute 'Accuracy'
猜你喜欢
  • 2014-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多