Move self.variable = 5 to before self.y = Y(self). When Y is initialized, variable has yet to be set in the parent. Since it is not a class attribute (it is defined only for the instance) it does not exist until then.
Getting an instance's attributes from a related instance
Question
Why is it that I cannot access the attribute of an object as seen in the following example? (raises an error)
class X(object):
def __init__(self):
self.y = Y(self)
self.variable = 5
class Y(object):
def __init__(self,parent):
self.parent = parent
print self.parent.variable
my_instance = X()
Error raised: AttributeError: 'X' object has no attribute 'variable'
Shouldn't variable
be accessible to the instance of Y
that is created when X
is initialized?
Solution
OTHER TIPS
You're instantiating before adding/initializing the variable
attribute. It will have no knowledge of the variable unless again instantiated or swapped as the other answer mentioned.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow