简体   繁体   中英

python subclass can't import superclass from superclass

First of all is very possible I can making a terrible mistake. But let's go!

My superclass (project/src/mlbase.py)

from preprocessing import PreProcessing

class MLBase:
  preProcessing = None

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

My Subclass(project/src/preprocessing.py)

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

My script that is instantiating everything(project/main.py)

from src.mlbase import MLBase

mlb = MLBase(preProcessingOptions = {})

Dirs

  """

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

  """

As you can see. The objective is instanciate subclasses from superclass. But I receive the following error when src/preprocessing.py module tries to import MLBase class from src.mlbase.py :

ImportError: cannot import name MLBase

Why this is happening?

It's just a little typo. You declared class MBase but tried to import MLBase . All you have to do is change the superclass file to this:

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...

The solution was import PreProcessing class using from preprocessing import PreProcessing inside the constructor method! I don't know why! I really would like to understand that!

In mlbase module:

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

In preprocessing module

from mlbase import MLBase

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

Too weird for me!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM