문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top