0
class GrandParent():
    def __init__(self, a, b):
        self._a = a
        self._b = b

    def blah(self):
        return "GP:" + self._a + self._b

class Parent2(GrandParent):
    def __init__(self, a, b, c):
        self._a = b
        self._b = a
        self._c = self.blah()

class Child2(Parent2):
    def __init__(self, a, b, c, d):    
        Parent2.__init__(self, a, b, c)

    def blah(self):
        return ("C2: " + self._a + self._b
        + self._c + self._d)


c2 = Child2("A", "B", "C", "D")

Here is the code I am supposed to trace. I create an object c2 of Child2. I go in Child2.__init__. I go in Parent2.__init__. I initialize self._a, self._b.

My problem is with self._c.

Parent2 does not have a blah() method, so I would expect it to get self._c from GrandParent.blah(), but instead it goes to the Child2.blah(). Why does this occur?

3
  • In your example Child2 needs to be a subclass of Parent2 (it currently says Parent1). The edit is too small for me to fix it. Commented Dec 10, 2016 at 1:46
  • @P-robot done, there were several other improvements that could be made so the edit was big enough. Commented Dec 10, 2016 at 1:50
  • Actually this is a code snippet part of something bigger, but the Parent1 did not play a factor, neither did classes like Child1, so I removed them because they weren't relevant to my problem Commented Dec 10, 2016 at 2:10

1 Answer 1

1

Because self is a direct instance of Child2 so self.blah() must be the equivalent of Child2.blah(self). That the code happens to be in a method of a parent of Child2 just before that call is not relevant.

Sign up to request clarification or add additional context in comments.

2 Comments

Ohhhh .... but in the case that Child2 did not ahve blah , then would it call the parent?
Yes. More specifically it will look through Child2.__mro__ (method resolution order) and pick the first one that has the method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.