JUGAL SHAH
JUGAL SHAH

Reputation: 46

Calling child method to parent class and getting error related to no attribute

Following is a sample code. I am trying to implement similar in an extensive code.

I have performed enough research about it but I could not find any specific explanation related to my problem.

class A:
    def __init__(self,a,b):
        self.a = a
        self.b = b
        self.e = self.gete()
    def typing(self):
        return self.d
    def gete(self):
        return self.d +1

class B(A):
    def __init__(self,a,b,c):
        super().__init__(a,b)
        self.c = c
        self.d = self.getd()

    def getd(self):
        return self.c+1

kk = B(1,2,3)
print(kk.typing())
print(kk.e)

My expected result is 5. But instead, it is raising an error.

"AttributeError: 'B' object has no attribute'" But in fact it has a line "self.d = self.getd()".

Upvotes: 0

Views: 791

Answers (1)

kindall
kindall

Reputation: 184200

In your B.__init__(), you call super().__init__() before you assign self.d. Therefore, at the time you call A.__init__(), there is no d attribute on the object, so A.gete() fails.

To fix this, you can call super().__init__() after setting self.d in B.__init__().

Upvotes: 2

Related Questions