0

In python3, how do i create objects with an instance name and multiple arguments from a list? I have an example here. I need a way to initialize in a for loop with variable names that allow me to access the instance later.

class fruit():
    def __init__(self, color, weight):
        self.color = color
        self.weight = weight

    def scale(self):
        print(f"{self.weight} kg")


# i can do
strawberry = fruit("red", 10)
strawberry.scale()
# output "10 kg"

# but i cant do
fruitlist = [
    ["cherry", "red", 5],
    ["banana", "yellow", 10],
    ["blueberry", "blue", 15],
]

for i in range(len(fruitlist)):
    fruitname = fruitlist[i][0]
    fruitname = fruit(fruitlist[i][1], fruitlist[i][2])

cherry.scale()
# output "undefined name cherry"
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Tweakimp
  • 393
  • 5
  • 16
  • I dont see how this would help me. I already have a list of lists to store the fruit data, how am i supposed to put this into a dictionary? – Tweakimp Jan 02 '18 at 09:19
  • Don't use dynamic variables here, use a dictionary. Any answer that would allow you to create the variables dynamically would involve modifying the `globals()` dict *anyway*, so you might as well not clobber the global namespace and simply use a `dict` – juanpa.arrivillaga Jan 02 '18 at 09:20
  • A quick way: `fruitdict = {name:fruit(color, weight) for name, color, weight in fruitlist}` – juanpa.arrivillaga Jan 02 '18 at 09:22

0 Answers0