0

If I were to have a list aList = ['Apple', 'Banana', 'Cherry', 'Date'], and I wanted to make each item in the list an object, for example the equivalent of Banana = AClass(). After doing this, I would be able to create and call self.anything for each item in the list.

How would I go about doing this?
Here is essentially what I am trying to achieve:

import random
class Fruit:
   def __init__(self):
        self.tastiness = random.randint(1,10)

fruits = ['Apple', 'Banana', 'Cherry', 'Date']
fruits[1] = Fruit()   # Creating a variable from the list
if Banana.tastiness < 5:
    print('Not tasty enough')
AJ123
  • 194
  • 2
  • 14
  • Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – timgeb Sep 17 '18 at 17:10
  • I looked at that, I don't think that helps me – AJ123 Sep 17 '18 at 17:13
  • How not so? It's exactly your question and the answers here are basically duplicates of the answers in that topic. – timgeb Sep 17 '18 at 18:22

3 Answers3

4

Given your class and list of names, you could use a dict comprehension to create the fruit instances and have reasonable access to them via their names:

fruits = ['Apple', 'Banana', 'Cherry', 'Date']
fruits = {k: Fruit() for k in fruits}

if fruits['Banana'].tastiness < 5:
    print('Not tasty enough')

While it is possible to create variables with dynamic names (so that your Banana.tastiness would work), I would strongly advice against it.

user2390182
  • 72,016
  • 6
  • 67
  • 89
1

IIUC, this is what you want to do:

Using strings as key:

dfruits = {}
for f in fruits:
    dfruits[f] = Fruit()

Dict comprehension-style

dfruits = {i: Fruit() for i in fruits}

Using integer keys for the dict:

dfruits = {}
for i,f in enumerate(fruits):
    dfruits[i] = Fruit()

Or

dfruits = {i: Fruit() for i, _ in enumerate(fruits)}
Yuca
  • 6,010
  • 3
  • 22
  • 42
-1

You would likely go about doing this by creating a parent class "Fruit" with child classes for "Apple", "Banana" ect

Here is an article that describes the process for doing what you want.

https://www.digitalocean.com/community/tutorials/understanding-class-inheritance-in-python-3

I know you can create an array of objects, where the individual items inherit traits of their individual class, however, I believe these have to initialize your object of type fruit/specific fruit beforehand.

x = Apple()
x.taste = "bitter"
list.append(x)