I want to pass a self-reference down to an instantiated class (the child should have access to the parent). It works if everything is in one file like this:
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')
output is my parent is parent as expected
The 2-file version is this:
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)
and:
from ClassB import ClassB
class ClassA:
def __init__(self, name):
self.name = name
self.b = ClassB('myName', self)
if __name__ == '__main__':
a = ClassA('parent')
output is assert isinstance(parent, ClassA) AssertionError
That’s because the second passes a
__main__.ClassA, whereasClassBexpects aClassA.ClassA. Find a different way of doing this, such as puttingClassAin its own module.