2

I have rewritten a C# dependency inversion example in Python. I have created an interface called CalculatorOperation and trying to implement dependency injection via the Calculator constructor. The problem is when I run the code, it returns None. If I change self.calc_op = CalculatorOperation() to self.calc_op = Addition(), it returns the correct value of 15.

class CalculatorOperation():
    def calculate(self, num_1, num_2):
        pass


class Calculator:
    def __init__(self, calc_op):
        self.calc_op = CalculatorOperation()

    def solve(self, num_1, num_2):
        return self.calc_op.calculate(num_1, num_2)


class Addition(CalculatorOperation):
    def calculate(self, num_1, num_2):
        return num_1 + num_2


class Subtraction(CalculatorOperation):
    def calculate(self, num_1, num_2):
        return num_1 - num_2


def main():
    addition = Calculator(Addition())
    print(addition.solve(10, 5))


if __name__ == '__main__':
    main() # None

1 Answer 1

2

Just pass in the object that you created in main (don't re-do the initialization from within the __init__ method), like so:

class Calculator:
    def __init__(self, calc_op):
        self.calc_op = calc_op
Sign up to request clarification or add additional context in comments.

Comments

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.