【问题标题】:How can I import a python class which is in a sub directory, where the script and sub directory both have hyphens?如何导入子目录中的 python 类,其中脚本和子目录都有连字符?
【发布时间】:2021-09-30 14:19:37
【问题描述】:

下面是我的文件夹结构。

Main_Folder
|
|-my_script.py
|
|-level-1
    |--__init__.py
    |
    |--level-2
        |--__init__.py
        |
        |--new_script.py

新脚本是小代码sn-p

class check:
    def print_me():
        print("inside the class")

我正在尝试将其导入 my_script.py。 代码sn-p是:

import importlib

mod = importlib.import_module("level-1.level-2.new_script.check")

my_instance = check()

my_instance.print_me()

我收到以下错误:

Traceback (most recent call last):
  File "/home/danish/tuts/del_check/my_script.py", line 4, in <module>
    mod = importlib.import_module("level-1.level-2.new_script.check")
  File "/home/danish/anaconda3/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 970, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'level-1.level-2.new_script.check'; 'level-1.level-2.new_script' is not a package

我继续搜索solution。但是没有用。我在这里做错了什么。 另外,不能更改目录名称

【问题讨论】:

    标签: python-3.x python-importlib


    【解决方案1】:

    让我们先更新你的类方法:

    class check:
        def print_me(self):
            print("inside the class")
    

    然后我们可以导入模块。注意,check 是一个类,所以我们不要尝试将其作为模块导入。

    import importlib
    mod = importlib.import_module("level-1.level-2.new_script")
    my_instance = mod.check()
    my_instance.print_me()
    

    这应该给你:

    inside the class
    

    【讨论】:

    • 谢谢。我忘记了类定义中的 self 选项,并忘记将方法作为实例调用。谢谢。
    猜你喜欢
    • 2018-05-05
    • 2014-03-22
    • 2013-11-10
    • 1970-01-01
    • 2011-05-07
    • 2020-05-11
    • 2012-11-01
    相关资源
    最近更新 更多