automatic python variables

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • twohot
    New Member
    • Dec 2010
    • 8

    automatic python variables

    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)
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    If your code is encapsulated in a class instance:
    Code:
        for i, name in enumerate(book_list):
            setattr(self, "book%s" % (i), name)
    If not:
    Code:
    for i, name in enumerate(book_list):
        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.

    Comment

    • twohot
      New Member
      • Dec 2010
      • 8

      #3
      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
      Last edited by twohot; Dec 27 '10, 05:53 AM. Reason: missed a few points

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        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.

        Comment

        • twohot
          New Member
          • Dec 2010
          • 8

          #5
          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.

          Comment

          Working...