I have an instance of a class that i set the value to 'self.world' inside a class named 'zeus' inside a module named 'Greek_gods'. and i have another class names 'World' inside a module name 'World'.
How can i tell zeus to go to 'World' and get the instance self.world?
#module named World
class World():def __init__(self):self.world = Atlas()#module named Greek_gods
class zeus():def __init__(self)
You can't, because you cannot know the world instance to be added in Zeus
at the moment you create Zeus.
However, you can pass an instance of World
for Zeus
. There are various ways to do it:
Pass World
as a parameter to the constructor:
#module named greek_gods
class Zeus(object):def __init__(self, world):self.world = Atlas()world = World()
zeus = Zeus(world)
You can make World
to create Zeus
:
#module named World
class World(object):def __init__(self, world):self.world = Atlas()def create_zeus(self):zeus = Zeus() # It would be better to pass it as a constructor zeus.world = world # parameter but let us leave it simple# Using your classes:world = World()zeus = World.create_zeus()
You can create one special instance of World
in the world module:
#module named World
class World(object):def __init__(self):self.world = Atlas()
greek_world = World()#module named Greek_gods
import world
class Zeus(object):def __init__(self):self.world = world.greek_world
I would recommend to use the second solution; after that, the first one. The third one, however, can be very useful, too, specially if, by default, you need just one world in your application (the so-called singletons).