0

I have the following:

class Parent:

    @classmethod
    def add_2(cls, number):

        plus_1 = cls.add_1(number)
        plus_2 = cls.add_1(number)
        return plus_2

    def add_1(cls, number):

        return number + 1

class Child(Parent):

    @classmethod
    def add_1(cls, number):

        return number + 2

Child.add_1(5)
Child.add_2(5)

I want Child.add_2(5) to return 9, but it returns 7. Can anyone explain why this behavior is occurring? Its easy enough to fix it by overriding add_2 as well in the child class, but it seems overly clunky.

2
  • 2
    Is the lack of a @classmethod decorator for Parent.add_1 intentional? Commented Apr 3, 2018 at 15:35
  • return plus_1 + plus_2? Commented Apr 3, 2018 at 15:35

1 Answer 1

2

I assume that you're expecting Child.add_2(5) to return 9 based on the fact that:

  • Child.add_1 adds 2 to the argument it receives (initially 5)
  • Child.add_2 (inherited from Parent) calls Child.add_1 twice (so it would make sense that 5 + 2 + 2 = 9)

The problem is in Parent.add_2:

plus_1 = cls.add_1(number)
plus_2 = cls.add_1(number)

cls.add_1 is called twice, but the result of the 1st call (plus_1) is ignored, and the 2nd call starts from number which is 5, resulting 7.

To correct the problem (which I think it's a typo due to copy/paste), modify cls.add_1 2nd call to:

plus_2 = cls.add_1(plus_1)

to take the result of the 1st call into account.

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

1 Comment

Yes, it was a typo. Second call should be plus_2 = cls.add_1(plus_1). Purely the result of a typo! Whoops

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.