CornSmith
CornSmith

Reputation: 2037

Making two classes reference eachother

I'm trying to make a text adventure where different "place" classes can point to eachother.

For instance, I have a Manager class that has a reference to each place. Then I have a Home class, and a Club class, with references to eachother through manager. The problem is that I can't instantiate them due to the circular reference.

Here's how I solved it, but it's ugly, because I have to create the places member inside of a method instead of __init__.

class Manager:
  def __init__(self):
    self.home = Home(self)
    self.club = Club(self)

class Home:
  def __init__(self, manager):
    self.places = {}
    self.manager = manager

  def display_plot_and_get_option (self):
    print "where do you want to go?"
    return 'club' #get this from user

  def get_next_place(self, place_name):
    self.places = { #THIS IS THE BAD PART, which should be in __init__ but can't
      'home':self.manaer.home
      'club':self.manaer.club }
    return self.places[place_name]

class Club:
  #similar code to Home
  pass

manager = Manager()    
while (True):
  place_name = manager.current_place.display_plot_and_get_option()
  manager.current_place = manager.current_place.get_next_place(place_name)

In c++ I would set my dict up in the constructor, where it should be, and it would use the pointer of the Manager's home or club members, since I only want 1 instance of each place. How can I do this in python?

edit: expanded code example

Upvotes: 4

Views: 4405

Answers (2)

thikonom
thikonom

Reputation: 4267

You can just have a dictionary that holds the references, and call the methods straight from the Manager (which shouldn't really be named Manager, as it does not serve that purpose now) instance.

class Home(object):
    pass

class Club(object):
    pass

PLACES = {
   'home': Home(),
   'club': Club()
}

class Manager(object):
    def display_plot_and_get_option(self):
        return raw_input('Where do you want to go?')
   def get_next_place(self, place_name):
        return PLACES[place_name]

m = Manager()
while 1:
    place_name = m.display_plot_and_get_option()
    m.get_next_place(place_name)

Upvotes: 5

ben4808
ben4808

Reputation: 91

Assuming that Home and Club are just a couple of the many places you plan to include in your game, it would probably be advantageous to create a Place class. Specific classes can either inherit from Place or have a name as a data member. Then you can model connections with a tree or graph.

Upvotes: 2

Related Questions