Quote:The question means: I have a class that i want to instantiate and use by passing it to at least two other objects. But I don't want to instantiate that class in the main body, i would rather instantiate the class (create the object) inside another completely different object (possibly in its _init_ and share that instance with a completely seperate object.
This is certainly possible, but it is problematic.
let's say that you have three object (a, b and c) that all want to know about the same object which well call the "golden snitch". a creates the golden snitch. b and c somehow have to be told that the snitch exists. How can this be done?
1. Create a first. When creating b and c, pass them the golden snitch.
a = ClassA()
b = ClassB(a.golden_snitch)
c = ClassC(a.golden_snitch)
The problem with this approach is all three classes need to know about the golden snitch. If you make changes to the snitch you will have to change ClassA, ClassB and ClassC. Your main program also has to know about the snitch, and it has to know the snitch is created by ClassA and has to be passed as an argument when making instances of ClassB and ClassC.
This approach works, but it has a lot of inter-dependency issues.
2. A slightly better approach is to not have ClassA make the snitch, but rather do that in the main program. You might have a reason to avoid doing this (you said you have a reason), but it does make for a better design because you removed the dependency that ClassA has to be created first, and now you can create ClassB and ClassC objects without having to make a ClassC object.
snitch = GoldenSnitch()
b = ClassB(snitch) # Couldn't do this using pattern #1
3. A better approach yet is to not have any of the classes know about the snitch. In this pattern we write the program so the main program is the only one that knows about the snitch, the ClassA, ClassB and ClassC objects talk to the snitch through the main program (or a proxy created by the main program).
def catch_snitch(player):
snitch.catch(player)
a = ClassA()
a.catch_function = catch_snitch
b = ClassB()
b.catch_function = catch_snitch
c = ClassC()
c.catch_function = catch_snitch
snitch = GoldenSnitch()
ClassA knows it has to call some function, but it does not know anything about the function other than it passes a "player" argument. Objects can be created in any order, including the Snitch.
a = ClassA()
b = ClassB()
c = ClassC()
snitch = GoldenSnitch()
a.connect(snitch.catch)
b.connect(snitch.catch)
c.connect(snitch.catch)
And there are other approaches that provide different degrees of isolation along with different amounts of work to achieve that isolation.
4. A slight variation of pattern 3. is to have the snitch provide the function that gets called.