[Tutor] How to have unique identifiers for multiple object instances of a given class?
Alan Gauld
alan.gauld at yahoo.co.uk
Mon Aug 27 04:43:10 EDT 2018
On 27/08/18 04:58, boB Stepp wrote:
> So you are saying do something like:
>
> class SolitaireGame():
> def __init__(self, name):
> self.name = name
>
> def describe_self(self):
> print("This game of solitaire is called", self.name, ".")
>
> game_objects = {}
> def make_new_game_object(name):
> global game_objects
> game_objects[name[ = SolitaireGame(name)
>
> make_new_game_object('Chinese Solitaire')
> make_new_game_object('Ace Mastery')
> make_new_game_object('King Mastery')
Yes, although I'd miss out the function and just populate
the dict directly. A single line function doesn't really
help much unless its a very complicated line or one
that might change regularly (eg storing directly in
a database or file rather than in memory).
game_objects[name] = SolitaireGame(name)
If you are concerned about duplicates just add a
guard when you read the name:
while True:
name = input("Name: ")
if name in game_objects:
print ("duplicate name, try again")
else:
break
Maybe put that in a function...
>> Maybe JSON for that? Or even a shelve database?
>
> I plan to keep this simple. I will use a ".cfg" file to store game
> configuration information and a ".csv" file to store the actual
> records of hands played. But I will have to be careful how I generate
> the base filenames to avoid duplicates and potential nasty
> user-generated names. Though this project is only meant for my use
If you go with a single JSON file or shelve you have
no worries about name clashes. JSON is specifically
designed to store multiple complex object records.
And it retains the readability of CSV (unlike shelve).
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list