Dynamically naming objects.
Ben Finney
bignose+hates-spam at benfinney.id.au
Sat Jun 7 00:52:46 EDT 2008
Kalibr <space.captain.face at gmail.com> writes:
> what I want to do is have, say 5 users in a game, so I'd have to
> spawn 5 objects. I can't do that because I have'nt hardcoded any
> object names for them.
Python's built-in mapping type 'dict' is a good fit for this.
Given:
* a 'User' class that is initialised with the user's name
* some way of getting a sequence of names (that you haven't told us
yet), that I'll bind here to the name 'sequence_of_names'
You can then write::
game_users = {}
for name in sequence_of_names:
game_users[name] = User(name)
This will result in 'game_users' bound to a dict with names mapping to
separate instances of the 'User' type. These instances can each be
addressed by name from the 'game_users' mapping as
'game_users["Fred"]', etc.
--
\ "Pinky, are you pondering what I'm pondering?" "Well, I think |
`\ so, Brain, but do I really need two tongues?" -- _Pinky and |
_o__) The Brain_ |
Ben Finney
More information about the Python-list
mailing list