Python 当类位于同一文件中时,在父对象中创建子对象有效,但当类位于不同文件中时,创建子对象失败
我们开始:Python 当类位于同一文件中时,在父对象中创建子对象有效,但当类位于不同文件中时,创建子对象失败,python,python-2.7,inheritance,import,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() 太酷了,
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()
太酷了,它给了布雷克
但将这些类传播到不同的文件,即:
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
为什么它在一个案例中通过,而在另一个案例中失败?
有没有办法让它像在一个文件中一样工作?
回答发生了什么
解决方案
更改父类中的导入和调用使其在单独的文件中工作
import calls_inh.child_ppage
class Parent(object):
def doge(self):
print calls_inh.child_ppage.Child().doge_name
你的代码有很多问题,我不知道从哪里开始,但首先,在父类中创建子类的实例显然是个坏主意。这个问题更多的是关于python内部和行为,而不是好的实践:因此,你希望从导入a的B导入a,这无论如何都是不可能的。可能的重复