首页 > 解决方案 > 从 jupyter notebook 访问不同文件夹中的 python 文件中定义的 myclass

问题描述

我有以下文件夹结构

|
   |---notebook
   |      |
   |      --- MyNoteBook.ipnyb
   |
   |---python
   |     |
   |     --- image_rotation_utils.py

我在 python.image_rotation_utils.py 中有以下内容

class ImageRotationUtils:
    """ Utils for rotating images."""
    
    def __init__(self, image_path=None, image_name=None, output_path=None, output_annotations_file=None ):
        """ Initializes the class.
        Args:
            image_path: the relative path to the image
            image_name: image file name
            output_path: the relative path where rotated output file is stored.
            output_annotations_file: annotations file where rotated anotations are stored.
        """
        self.image_path = image_path
        self.image_name = image_name
        self.output_path = output_path
        self.output_annotations_file = output_annotations_file

    #other functions defined 

现在在 MyNoteBook.ipnyb 我有以下单元格

单元格 1:

import sys
    sys.path.insert(0, '..')
    from python.image_rotation_utils import *

上面现在在我下面的单元格 2 中成功执行

myUtils = ImageRotationUtils()

我得到以下错误

----> 1 ImageRotationUtils()

TypeError: __init__() missing 4 required positional arguments: 'image_path', 'image_name', 'output_path', and 'output_annotations_file'

为什么当我在构造函数中有默认值在类定义中没有 None 时出现此错误。

我是 python 新手,并试图以高效的方式编写代码。我犯了什么错误。请提供输入

标签: python-3.xjupyter-notebook

解决方案


您粘贴的内容对我来说看起来不错,并且您的代码对我来说没有错误。

  1. 也许该代码之前或之后的某些东西破坏了类定义?
  2. 也许您在 Jupyter 或 IPython 中运行它并且您ImageRotationUtils之前导入了,但随后更改了代码,并尝试再次重新导入 - 新的重新导入出现问题,因此您的定义没有被覆盖?如果是这种情况,请重新启动环境(或 Jupyter 中的内核)并重新运行代码。
  3. 我建议将一个简单的初始化代码(如构造函数行)放入同一个源文件中,并将其作为单独的进程执行,以测试这是代码还是环境问题。

为方便起见并避免调整sys.path代码,我建议PYTHONPATH在加载环境之前将 python 目录添加到环境变量中,这样您就可以导入。


推荐阅读