Thread: Why OOP?
View Single Post
Old Oct 7th, 2007, 12:48 PM   #29
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
When you have a small number of conditions in Python, one uses an if-statement. But if there are a large number of conditions that follow a common pattern, it's easier to use a dictionary:
python Syntax (Toggle Plain Text)
  1. commands = {
  2. "look" : me.look,
  3. "move" : me.move,
  4. "go" : me.move
  5. }
It can be used like this:
>>> commands["look"]
<bound method Player.look of <__main__.Player object at 0xb7dcf7ec>>
>>> commands["look"]()
You are in the foyer of a house...
Another useful technique in Python is the ability to turn a list as a set of arguments using "*". e.g.
>>> me.look()
You are in the foyer of a house...
>>> me.look(*[])
You are in the foyer of a house...
>>> me.move("west")
You are in a dark kitchen...
>>> me.move(*["east"])
You are in the foyer of a house...
Combining these two techniques:
python Syntax (Toggle Plain Text)
  1. commands = {
  2. "look" : me.look,
  3. "move" : me.move,
  4. "go" : me.move
  5. }
  6.  
  7. def parse(verb, *nouns):
  8. commands[verb](*nouns)
  9.  
  10. while True:
  11. parse(*raw_input(">").lower().split())
The above code is only a few lines, but will enable you to use commands such as "look" and "go west", and is easily extensible. It may be rather tricky to understand at first, but it may be worth taking the time to figure out how it works. If you've any questions, don't hesitate to ask! Sometimes I'm not all that clear.
Arevos is offline   Reply With Quote