samedi 1 avril 2017

Python staticmethod and dependency injection

Can someone help me with a good explanation on why a staticmethod on python is useful for dependency injection?

I was seeing this great video https://www.youtube.com/watch?v=E_kZDvwofHY and on 45m45s Thomas Wouters claim that staticmethods are useful for DI, but I can't grasp why.

...

After start to writing this post, and made some tests I think I got it. An example:

class GreetPrint(object):

    def pp(self, param):
        print("Hello", param)


class User(object):

    def __init__(self, param):
        self.param = param

    def print_user(self):
        self.output(self.param)

    @staticmethod
    def output(msg):
        return print_dependency.pp(msg)


print_dependency = GreetPrint()

a = User("Guido")
a.print_user()

This is a better approach (at least in Python) than injecting through the constructor?

Aucun commentaire:

Enregistrer un commentaire