0

I'm trying to learn and understand dependency injection. (python example below):

class Printer :
    def print(self):
        pass


class CSVPrinter(Printer) :
    def print(self, data):
        for i in data:
            print(str(i)+ ";", end ="")


class PlainPrinter(Printer) :
    def print(self, data):
        for i in data:
            print(str(i)+ " ", end ="")

class Product:  
    def __init__(self, name, price, printer):
        self.name = name
        self.price = price
        self.printer = printer 
    def print(self):
        tab=[self.name, self.price]
        self.printer.print(tab)
 
printer = PlainPrinter()
prod = Product("prod1", "22", printer)
prod.print()

So I do understand, that doing it, I can simply inject PlainPrinter or CSVPrinter into Product, so that Product can behave in a different way. But in both cases, I need to somehow pass Product's data outside (to the Printer) so that it can operate on it (like in the Product.print())... -so in fact I could also have some "getter" in Product, that returns data, and then I can operate on it, without any coupling at all, so what's the point?

1 Answer 1

0

Yes, dependency injection is just passing (injecting) one object into another instead of requesting it. Nothing special, but it allows you to reuse objects in different combinations, change their lifecycle and so on.

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.