Python OOP - Class relationships
oop, python
Solution
I would go with Dependency Injection: instantiate a `GameClass` with the required `FieldClass` and `PlayerClass` in the constructor call etc. (i.e. instead of creating the dependent objects from within `GameClass` as you are doing at the moment).
class GameClass:
def __init__( self, fc, pc ):
self.Field = fc
self.Player = pc
class PlayerClass:
def __init__( self, fc ):
self.fc = fc
def DoMagicHere( self ):
# use self.fc
pass
fc=FieldClass()
pc=PlayerClass(fc)
gc=GameClass(fc, pc)
With DI, you can easily have access to the members you require once the setup phase is completed.
Problem
Assuming I have a system of three Classes. The `GameClass` creates instances of both other classes upon initialization. ``` class FieldClass: def __init__( self ): return def AnswerAQuestion( self ): return 42 class PlayerClass: def __init__( self ): return def DoMagicHere( self ): # Access "AnswerAQuestion" located in the "FieldClass" instance in "GameClass" pass class GameClass: def __init__( self ): self.Field = FieldClass() self.Player = PlayerClass() ``` What would be the best way of accessing `AnswerAQuestion()` located in `FieldClass` from within the instance of `PlayerClass`? - Do I have to pass a reference to the `FieldClass` instance to `PlayerClass`? - Is there another, better way of solving this? Doing the above would make me have to include an additional variable in `PlayerClass` to hold the `FieldClass` instance. - Is there a completely different way of managing class relationships in Python?