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')
3
  • Possible duplicate of How do I create a variable number of variables? Commented Sep 17, 2018 at 17:10
  • I looked at that, I don't think that helps me Commented Sep 17, 2018 at 17:13
  • How not so? It's exactly your question and the answers here are basically duplicates of the answers in that topic. Commented Sep 17, 2018 at 18:22

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.