Can someone explain to me how to return a new instance of a class by iterating over a list of names and a list of dicts?
I know that I can unpack my dictionary using **, and I know that I can iterate through my list of dictionaries.
So I attempted to create a for loop function that creates new instances of my Card class for each card in the cardList.
Here is the code I thought would work:
def createCardInstances(x):
for i in range(len(x)):
namesOfCards[i] = Card(**cardList[i])
return namesOfCards[i]
namesOfCards is a list of card names that I would like to turn into instances of the Card class. cardList is a list of the dictionaries that represent cards and their values.
For instance, I can do this:
Knight = Card(**cardList[0])
Which works fine. But, if I'm developing a card game and have upwards of a 100 individual cards or more, I would like to avoid having to write out each card name individually and copy\pasting the =Card(**cardList[]) code each time.
How do I automate the creation of new instances? Is that even feasible?
EDIT:
I'm trying to use the names in namesOfCards to make new instances of Card. It was suggested to me that my next step in learning python while creating a card game was to make it more object oriented.
So my goal right now is to use the names of the cards - saved in the list namesOfCards - to make new instances of Card. i.e.:
[Knight, Mage, Warrior, ...]
And I want to have the ability to take those and do this:
Knight = Card(**cardList[0])
Mage = Card(**cardList[1])
Warrior = Card(**cardList[2]
and so on and so forth.
Is that possible? Or do I need to use the list comprehension suggestion to store all of the class instances into a list, and then have to access the instances by using new_cards[0].name or new_cards[1].attack?
**(cardList[i])KnightorMageby callingprint Knight.attack- I getNameError: name 'Knight' is not defined.createCardInstancesto return? Because right now, it's returning a single Card after a single iteration of your loop, and no other Card gets a chance to be initialized.