一句话,您在这里要担心的正式术语是Separation of Concerns。
In response to your specific example, which of the two examples you choose depends on the concerns solved by FooBar
and bar
. If bar
is in the same problem domain as FooBar
or if it otherwise makes sense for FooBar
to store a reference to bar
, then the second example is correct. For instance, if FooBar
has multiple methods that accept a bar
and if you always pass the same instance of bar
to each of a particular FooBar
instance's bar
-related methods, then the prior example is correct. Otherwise, the latter is more correct.
Ideally, each class you create should model exactly one major concern of your program. This can get a bit tricky, because you have to decide the granularity of "major concern" for yourself. Look to your dependency tree to determine if you're doing this correctly. It should be relatively easy to pull each individual class out of your program and test it in isolation from all other classes. If this is very difficult, you haven't split your concerns correctly. More formally, good separation of concerns is accomplished by designing classes which are cohesive and loosely coupled.
While this isn't useful for the example you posted, one simple pattern that helps accomplish this on a broader scale is Inversion of Control (IoC, sometimes called Dependency Injection). Under IoC, classes are written such that they aren't aware of their dependencies directly, only the interfaces (protocols in Python-speak) which their dependencies implement. Then at run time, typically during application initialization, instances of major classes are created by factories, and they are assigned references to their actual dependencies. See this article (with this example) for an explanation of how this can be accomplished in Python.
Finally, learn the four tenets of object-oriented programming.