在同一文件中创建父类的子对象有效,但在不同文件中失败

0 投票
1 回答
1205 浏览
提问于 2025-04-28 13:12

我们开始吧:

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
  1. 回答关于 Python中的循环依赖 会发生什么

  2. 解决方案 如何避免Python中的循环导入? 通过改变父类中的导入和调用,使其在不同文件中正常工作

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

撰写回答