ImportError: cannot import name MainClass

时光总嘲笑我的痴心妄想 提交于 2019-12-24 07:17:33

问题


society. I'm trying to understand the OOP programming and I'm facing some issues and asking for help.

Here the example:

I'm trying to create all objects under one class and then I want to inherit from this class.

test_class/baseclass.py

from test_class.first_class import FirstClass
from test_class.second_class import SecondClass


class MainClass:
    def __init__(self):
        self.firstclass = FirstClass()
        self.secondclass = SecondClass()

test_class/first_class.py

from test_class.baseclass import MainClass

    class FirstClass(MainClass):
        def __init__(self):
            MainClass.__init__(self)

        def add_two_number(self):
            return 2 + 2

test_class/second_class.py

from test_class.baseclass import MainClass

class SecondClass(MainClass):
    def __init__(self):
        MainClass.__init__(self)

    def minus_number(self):
        return self.firstclass.add_two_number() - 10


if __name__ == '__main__':
    print(SecondClass().minus_number())

When I run the last file I get this error

Traceback (most recent call last):
  File "/Users/nik-edcast/git/ui-automation/test_class/second_class.py", line 1, in <module>
    from test_class.baseclass import MainClass
  File "/Users/nik-edcast/git/ui-automation/test_class/baseclass.py", line 1, in <module>
    from test_class.first_class import FirstClass
  File "/Users/nik-edcast/git/ui-automation/test_class/first_class.py", line 1, in <module>
    from test_class.baseclass import MainClass
ImportError: cannot import name MainClass

it's just an example, but I have different code. and I'm looking for a solution based on this example


回答1:


I changed your code to this:

baseclass.py

import first
import second

class MainClass:
    def __init__(self):
        self.firstclass = first.FirstClass()
        self.secondclass = second.SecondClass()

first.py

import baseclass

class FirstClass(baseclass.MainClass):
    def __init__(self):
        baseclass.MainClass.__init__(self)

    def add_two_number(self):
        return 2 + 2

second.py

import baseclass

class SecondClass():
    def __init__(self):
        baseclass.MainClass.__init__(self)

    def minus_number(self):
        return self.firstclass.add_two_number() - 10

if __name__ == '__main__':
    print(second.SecondClass().minus_number())

I get no ImportErrors or any errors of any kind. I think your ImportError had something to do with from instead of just import. I hope this helps.



来源:https://stackoverflow.com/questions/50312470/importerror-cannot-import-name-mainclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!