0

Here we go:

class Parent(object):
    def doge(self):
        print Child().doge_name

class Child(Parent):
    def __init__(self):
        super(Child, self).__init__()
        self.doge_name = 'Burek'

if __name__ == '__main__':
    Parent().doge()

So cool - its gives Burek

But spreading this classes to different files i.e.:

from calls_inh.child_ppage import Child

class Parent(object):
    def doge(self):
        print Child().doge_name

if __name__ == '__main__':
    Parent().doge()

other file:

from calls_inh.parent_page import Parent


class Child(Parent):
    def __init__(self):
        super(Child, self).__init__()
        self.doge_name = 'Burek'

returns:

 Traceback (most recent call last):   File
 "D:/check/calls_inh/parent_page.py", line 1, in <module>
     from calls_inh.child_ppage import Child   File "D:\check\calls_inh\child_ppage.py", line 1, in <module>
     from calls_inh.parent_page import Parent   File "D:\check\calls_inh\parent_page.py", line 1, in <module>
     from calls_inh.child_ppage import Child ImportError: cannot import name Child

 Process finished with exit code 1
  1. Why it pass in one case and fails in other?
  2. Is there any way to make it works like in one file?
pbaranski
  • 22,778
  • 19
  • 100
  • 117
  • 2
    There are many problems of your code I don't know where to start, but first, it's definetly a bad idea to create an instance of subclass in parent class. – laike9m Oct 20 '14 at 12:18
  • This question is more about python internals and behaviour than good practices :) – pbaranski Oct 20 '14 at 12:38
  • So, you're expecting to import A from B that import A, this is impossible, in any way. – laike9m Oct 20 '14 at 12:41
  • 2
    possible duplicate of [Python circular importing?](http://stackoverflow.com/questions/22187279/python-circular-importing) – Korem Oct 20 '14 at 12:41

1 Answers1

0
  1. Answer what happens Circular dependency in Python

  2. Solution How to avoid circular imports in Python? changing import and call in parent class make it work in separate files

    import calls_inh.child_ppage
    
    class Parent(object):
       def doge(self):
           print calls_inh.child_ppage.Child().doge_name
    
Community
  • 1
  • 1
pbaranski
  • 22,778
  • 19
  • 100
  • 117