0

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
asked Aug 3, 2016 at 7:15
6
  • Inheritance is meant to be a top-down hierarchy, not a matrix. You should reconsider your design. Commented Aug 3, 2016 at 7:18
  • What to do if my child class need to use a method from parent class. Commented Aug 3, 2016 at 7:20
  • That's fine, it's the other direction (parent using child's method) that breaks the rules. Commented Aug 3, 2016 at 7:21
  • two.py calling one.py but one.py require two.py... It is paradox... Commented 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. Commented Aug 3, 2016 at 7:28

1 Answer 1

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.

answered Aug 3, 2016 at 7:20
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.