S
S
Sazoks2021-05-01 17:38:04
Software design
Sazoks, 2021-05-01 17:38:04

Can a class implementation depend on external modules?

Good day to all!
Here I have a class. This class internally uses some object of another class.
I see two options for implementing this:

  1. Pass the required object of another class (reference) to the class constructor and use it internally.
  2. If this other object of a different class is already in some other file, import it into the file with our class and use it in the code.

I do not like the 2nd option, because the very implementation of the class inside depends on the presence of another object somewhere from the outside.
Python example:
from file_b import ClassB

class A:
    def __init__(self, b: ClassB):
        self.__b = b
        # Дальше используем уже self.__b.

Or
from file_b import b

class A:
    def __init__(self):
        pass
    
    def some_fun(self):
        b.some_method_b()


I really hope for your opinion!
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-05-01
@Sazoks

That's right. It is better to pass dependencies through the constructor

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question