python-3.x - 从 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 新手,并试图以高效的方式编写代码。我犯了什么错误。请提供输入
解决方案
您粘贴的内容对我来说看起来不错,并且您的代码对我来说没有错误。
- 也许该代码之前或之后的某些东西破坏了类定义?
- 也许您在 Jupyter 或 IPython 中运行它并且您
ImageRotationUtils
之前导入了,但随后更改了代码,并尝试再次重新导入 - 新的重新导入出现问题,因此您的定义没有被覆盖?如果是这种情况,请重新启动环境(或 Jupyter 中的内核)并重新运行代码。 - 我建议将一个简单的初始化代码(如构造函数行)放入同一个源文件中,并将其作为单独的进程执行,以测试这是代码还是环境问题。
为方便起见并避免调整sys.path
代码,我建议PYTHONPATH
在加载环境之前将 python 目录添加到环境变量中,这样您就可以导入。
推荐阅读
- chat - 在 AIML 中与不同用户进行多次对话
- google-apps-script - 是否有替代 onEdit(e) 的方法?
- python - 在 Flask 应用程序中为 dash 应用程序创建 dockerfile
- c++ - 如何遍历可扩展散列结构的元素(特别是集合)
- arrays - 使用对象从数组发出 Laravel 请求
- java - WinAppDriver 如何在 Java 中定义一个 WindowsElement 而不会得到 java.lang.ClassCastException
- javascript - 正则表达式查找tml标签c#之外的任何文本
- python - 正则表达式提取包含三个元音的单词
- excel - 查找动态范围的列和行 VBA 的最小值、最大值和平均值
- c++ - 带有额外条件的 cin.fail C++