I am having 2 Python files in same directory. one.py and two.py containing classes First and Second respectively. I want import classes and inherit each other and use methods defined in each other.
one.py
from two import Second
class First(Second):
def first(self):
print "first"
two.py
from one import First
class Second(First):
def second(self):
print "second"
while compiling I am getting following error. Is there any way I can overcome this. Please suggest alternative methods also.
Traceback (most recent call last):
File "C:\Users\uvijayac\Desktop\New folder\two.py", line 1, in <module>
from one import First
File "C:\Users\uvijayac\Desktop\New folder\one.py", line 1, in <module>
from two import Second
File "C:\Users\uvijayac\Desktop\New folder\two.py", line 1, in <module>
from one import First
ImportError: cannot import name First
-
Inheritance is meant to be a top-down hierarchy, not a matrix. You should reconsider your design.cdarke– cdarke2016年08月03日 07:18:34 +00:00Commented Aug 3, 2016 at 7:18
-
What to do if my child class need to use a method from parent class.Unnikrishnan V– Unnikrishnan V2016年08月03日 07:20:44 +00:00Commented Aug 3, 2016 at 7:20
-
That's fine, it's the other direction (parent using child's method) that breaks the rules.cdarke– cdarke2016年08月03日 07:21:48 +00:00Commented Aug 3, 2016 at 7:21
-
two.py calling one.py but one.py require two.py... It is paradox...redratear– redratear2016年08月03日 07:23:38 +00:00Commented Aug 3, 2016 at 7:23
-
Yes. What can I do for that? Actually in my case methods in child class was originally inside parent class. For some reason i need to take them out and create a new py file and a new class with modules taken out. I want to use methods of child also, By importing parent class, I could do that before creating new py file.Unnikrishnan V– Unnikrishnan V2016年08月03日 07:28:18 +00:00Commented Aug 3, 2016 at 7:28
1 Answer 1
The actual problem you're encountering is that you're trying to do a circular import, which has nothing to do with your circular inheritance. (There's plenty of material on SO on how to avoid that.)
However, note that circular inheritance is also not possible, as a class is only available for subclassing once it's defined, and its definition includes being subclassed from the other class, which therefore also needs to already be defined, which requires... you get the point - you can't have circular inheritance.