我想将自引用传递给实例化类(子级应该可以访问父级)。如果所有内容都在一个文件中,则它可以工作,如下所示:
class ClassB:
def __init__(self, name, parent):
assert isinstance(parent, ClassA)
self.name = name
self.parent = parent
print('my parent is', parent.name)
class ClassA:
def __init__(self, name):
self.name = name
self.b = ClassB('child', self)
a = ClassA('parent')
输出my parent is parent
符合预期
2文件版本是这样的:
class ClassB:
def __init__(self, name, parent):
from ClassA import ClassA
assert isinstance(parent, ClassA)
self.name = name
self.parent = parent
print('my parent is', parent.name)
和:
from ClassB import ClassB
class ClassA:
def __init__(self, name):
self.name = name
self.b = ClassB('myName', self)
if __name__ == '__main__':
a = ClassA('parent')
输出是assert isinstance(parent, ClassA) AssertionError