By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,427 Members | 1,378 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,427 IT Pros & Developers. It's quick & easy.

automatic python variables

P: 8
I'm looking for ways to create variables in python3 as needed. E.g

book1 = book(name1) # book is a class
book2 = book(name2)
book3 = book(name3)
book4 = book(name4)
book5 = book(name5)
:
:
:
V
book-n = book(name-n)

I have the names of the book in a list but want to load those into class instances to take advantage off OOP. I could assign five to ten class objects like above but what if I have up a 100 books to deal with. Any way to generate those variables? (Note: Its not a code about books ... the above is a sample scenario)
Dec 25 '10 #1

✓ answered by bvdet

You could create a class instance for each book to contain the book data. Maintaining the data in an XML or SQL file may be the best route for significant amounts of data.

Share this Question
Share on Google+
4 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
If your code is encapsulated in a class instance:
Expand|Select|Wrap|Line Numbers
  1.     for i, name in enumerate(book_list):
  2.         setattr(self, "book%s" % (i), name)
If not:
Expand|Select|Wrap|Line Numbers
  1. for i, name in enumerate(book_list):
  2.     exec "%s = %s" % ("book%s" % (i), name)
It's better to maintain the list of books in a list or dictionary instead of creating a variable for each one.
Dec 27 '10 #2

P: 8
And what if you plan to do more than list the books? Say, be able to access each book's properties eg. chapters, publisher, author, genre, revisions. Would a dictionary still do?

Wouldn't it be better to have a list of object 'books' where the enumeration serves as a serial/key. eg book[1],book[2] ....book[n], each managing its own little db? or is SQL better off at this kind of thing?

Just thinking ...:o, Like I said, its really not about books. What I'm doing is more dynamic. The next time the code runs, those serials need not be the same for each item
Dec 27 '10 #3

bvdet
Expert Mod 2.5K+
P: 2,851
You could create a class instance for each book to contain the book data. Maintaining the data in an XML or SQL file may be the best route for significant amounts of data.
Dec 27 '10 #4

P: 8
That's what I thought ... since I don't anticipate anything more than a few thousands of files-lines (for the properties and not instances .....well, looking at about 10 to 20 instances at most). I'd probably go the 'class' way. I don't really plan to hold much in memory anyway, so the class object overhead shouldn't be significant.
Dec 27 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.