【问题标题】:Can not import a class from another file in the same directory in Python无法从 Python 中同一目录中的另一个文件导入类
【发布时间】:2018-08-26 20:14:49
【问题描述】:

我对 Python 还是很陌生,而且我还在习惯它。我有一个项目是使用一堆只包含函数定义的文件编写的。我决定在 OOP 范式中重新制作它,所以会发生这种情况:

那时,我有这两个文件:

Main
 | ---- loggingManager.py
 | ---- servoManager.py

在我拥有的 serverManager.py 脚本中:

from loggingManager import *
...
from time import sleep

一切正常。我可以毫无问题地使用 loggingManager.py 中的所有def函数。

现在我是这样的:

Main
 | ---- Logger.py
 | ---- ConfigurationWrapper.py

ConfigurationWrapper 的内容是:

import configparser

class ConfigurationWrapper:
    default_path = '/home/pi/Desktop/Bree/config.ini'

    def __init__(self, path_to_file=None):
        if path_to_file is None:
            path_to_file = self.default_path
...

Logger 看起来像这样:

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwarg$
        else:
            cls._instances[cls].__init__(*args, **kwargs)

        return cls._instances[cls]

class Logger():
    __metaclass__ = Singleton

我的目标是导入:

import ConfigurationWrapper

在 Logger.py 脚本文件中,但每次我这样做时,都会出现错误(通过在 MacOS 上的终端中输入“python Logger”):

Traceback (most recent call last):
  File "Logger", line 1, in <module>
    import ConfigurationWrapper
ImportError: No module named ConfigurationWrapper

我尝试在同一文件夹中添加空的 __ init __.py 文件,但仍然没有任何反应。

【问题讨论】:

    标签: python python-2.7 oop singleton


    【解决方案1】:

    尝试在导入的模块前添加一个点 (.)

    import .ConfigurationWrapper

    或者导入你的类

    from .ConfigurationWrapper import ConfigurationWrapper

    点 (.) 表示您正在从同一目录导入。

    【讨论】:

    • 这两个都不起作用。在第一种情况下,我在点上得到“无效语法”,在第二种情况下,在非包中尝试相对导入。
    【解决方案2】:

    我解决它的方法是添加:

    execfile("./ConfigurationWrapper")
    

    但我想知道这有多合适。

    【讨论】:

      猜你喜欢
      • 2020-02-03
      • 2023-02-02
      • 2021-10-06
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      • 2019-06-27
      • 2021-12-20
      相关资源
      最近更新 更多