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)
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)

Edited 6 Years Ago by twohot: typo errors

The easiest solution would be to use a list, and simply append each new object to the list in a loop. To follow your book list example, here's a sample program that does what you seem to be looking for:

class Book (object):
    def __init__(self, title):
        self.title = title

titles = ("The Joy of Snackes", "Tales of Beedle the Bard", "One Human Minute",
          "The King in Yellow", "The Fragile Path", "The Necronomicon")

books = []
for index, title in enumerate(titles):

(I included the part about enumerating the loop just to show how you could then access the individual objects with an index, even in the loop that creates them if needed. You probably don't need to do it quite this way.)

Edited 6 Years Ago by Schol-R-LEA: n/a

Its Perfect! ... though the (object) parameter is redundant ... but yes, this is what I've been looking for.

Thanks a lot.

Edited 6 Years Ago by twohot: forgot to say thanks

This question has already been answered. Start a new discussion instead.