Python Forum
Create class instances from list of strings
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create class instances from list of strings
#1
I have a list of strings as follows: somewords = ['apple', 'orange', 'pear']
I want to be able to have attributes for these words.
So I create a class as follows:

class Word():
...def __init__(self):
......self.size = ""
......self.color = ""
......self.fresh = bool
......self.age = int

and I would like to create instances of the class Word from my list like this:

apple = Word()
apple.size = 'big'
apple.color = 'red'
apple.fresh = True
apple.ageindays = 3

orange = Word()
orange.size = 'small'
orange.color = 'yellow'
orange.fresh = False
orange.ageindays = 10

If I could convert the strings in the list to variables I could simply iterate across the list to create the instances of the Word class. But I don't think this can be done or is there some other way to create instances of class from a list of strings?









o
Reply
#2
I would put them in a dictionary:

words = {word': Word() for word in somewords}
Getting the attributes in is another question, but you could probably make them parameters to __init__, and then load them in while creating the dict.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to read module/class from list of strings? popular_dog 1 424 Oct-04-2023, 03:08 PM
Last Post: deanhystad
  Trying to understand strings and lists of strings Konstantin23 2 699 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  problem in using int() with a list of strings akbarza 4 647 Jul-19-2023, 06:46 PM
Last Post: deanhystad
Question [solved] Classes, assign an attributes to a class not to instances.. SpongeB0B 4 891 May-20-2023, 04:08 PM
Last Post: SpongeB0B
  Delete strings from a list to create a new only number list Dvdscot 8 1,466 May-01-2023, 09:06 PM
Last Post: deanhystad
  Help with Logical error processing List of strings dmc8300 3 1,033 Nov-27-2022, 04:10 PM
Last Post: Larz60+
  [split] why can't i create a list of numbers (ints) with random.randrange() astral_travel 7 1,454 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  Splitting strings in list of strings jesse68 3 1,704 Mar-02-2022, 05:15 PM
Last Post: DeaD_EyE
  Cannot convert the series to <class 'int'> when trying to create new dataframe column Mark17 3 8,389 Jan-20-2022, 05:15 PM
Last Post: deanhystad
  how to easily create a list of already existing item CompleteNewb 15 3,386 Jan-06-2022, 12:48 AM
Last Post: CompleteNewb

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020