python子类无法从超类导入超类

时间:2019-01-04 18:58:15

标签: python oop inheritance

首先我很有可能犯一个可怕的错误。但是,走吧!

我的超类(project / src / mlbase.py)

from preprocessing import PreProcessing

class MLBase:
  preProcessing = None

  def __init__(self,preprocessingOptions):
    self.preProcessing = PreProcessing(preProcessingOptions)
    # and more stuff here...

我的子类(project / src / preprocessing.py)

from mlbase import MLBase
class PreProcessing(MLBase):
  def __init__(self,options):
     #processing options here... 
     pass 

我的实例化所有内容的脚本(project / main.py)

from src.mlbase import MLBase

mlb = MLBase(preProcessingOptions = {})

Dirs

  """

  project
  |
  + src
    |
    + mlbase.py
    |
    + preprocessing.py 
  |
  + main.py

  """

如您所见。目的是要实例化超类的子类。但是当src/preprocessing.py模块尝试从MLBase导入src.mlbase.py类时,我收到以下错误:

  

ImportError:无法导入名称MLBase

为什么会这样?

2 个答案:

答案 0 :(得分:1)

这只是一个小错字。您声明了class MBase,但是尝试导入MLBase。您要做的就是将超类文件更改为此:

from preprocessing import PreProcessing

class MLBase: #Note that it's "MLBase", not "MBase"
  preProcessing = None

  def __init__(self,preprocessingOptions):
    self.preProcessing = PreProcessing(preProcessingOptions)
    # and more stuff here...

答案 1 :(得分:0)

解决方案是在构造函数方法中使用from preprocessing import PreProcessing导入PreProcessing类!我不知道为什么!我真的很想明白!

在mlbase模块中:

class MLBase:
    def __init__(self,preProcessingOptions):
        from preprocessing import Preprocessing
        # more stuff

在预处理模块中

from mlbase import MLBase

class PreProcessing(MLBase):
    def __init__(self,preProcessingOptions):
        # more stuff

对我来说太奇怪了!