1

I've encountered a problem where, during the initialization of my main class, I create an instance of another class and attach it to an attribute:

# DOES NOT WORK (game instance not initialised yet)
class Bar:
    def __init__(self):
        self.radius = game.object_one.width / 2

class Game:
    def __init__(self):
        self.object_one = Foo()
        self.object_two = Bar()

game = Game()

I was able to overcome this by simply passing the instance as a parameter:

class Bar:
    def __init__(self, obj):
        self.radius = obj.width / 2


class Game:
    def __init__(self):
        self.object_one = Foo()
        self.object_two = Bar(self.object_one)

game = Game()

This seems quite a band-aid solution for a seemingly simple problem. Is there a nicer way of doing this? Or is this entire problem a result of bad code? How can it be avoided in the future?

  • 3
    It is not a band-aid solution, it's called dependency injection, a very common pattern. There are some frameworks that can help you make it nicer, but overall, it's not a bad solution. See https://en.wikipedia.org/wiki/Dependency_injection – user3738870 Aug 28 '22 at 22:00
  • Glad to know it's not a bad solution. Never heard of dependency injection before but I think I've ran into it before a few times. Thanks, this is exactly what I was looking for though. –  Aug 28 '22 at 22:06
  • Great, I've also added it as an answer:) – user3738870 Aug 29 '22 at 08:49

1 Answers1

1

Your second code snippet is not a band-aid solution, it is actually a very common pattern called dependency injection. Frameworks have been developed to make it nicer (mainly shorter), but overall, it's not a bad solution without the usage of any of these frameworks either. One example of such a framework is Dependency Injector, but there are several alternatives.

user3738870
  • 1,415
  • 2
  • 12
  • 24