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

2024-10-02 16:30:48 发布

您现在位置:Python中文网/ 问答频道 /正文

开始吧:

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

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

^{pr2}$

其他文件:

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. 有没有办法让它像在一个文件中一样工作?在

Tags: namefromimportselfchildinitdefpage