父类中的子对象在同一文件中的类中工作,但在单独的文件中的类时失败

时间:2014-10-20 12:05:14

标签: python python-2.7 inheritance import

我们走了:

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()

太酷了 - 它给了Burek

但是将这些类传播到不同的文件,即:

from calls_inh.child_ppage import Child

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

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

其他档案:

from calls_inh.parent_page import Parent


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

返回:

 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. 为什么它通过一个案件而在另一个案件中失败?
  2. 有没有办法让它像在一个文件中一样工作?

1 个答案:

答案 0 :(得分:0)

  1. 回答Circular dependency in Python

  2. 发生的事情
  3. 解决方案How to avoid circular imports in Python? 更改导入并在父类中调用使其在单独的文件中工作

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