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)

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):
    books.append(Book(title))
    print(books[index].title)

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

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

Thanks a lot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.