1

So I have a .txt list of "triggers." What I want to do is access this list of triggers, determine the trigger name, then use that name to point to a new instance of a class I have, call it WordTrigger. I have no idea how I would go about doing that. If I knew the variables, I could simply assign the class to a variable through var = WordTrigger(parameters). But the whole premise of the problem is that I do not know the variables and must find out their names through scanning the list. I realize that I could create a name attribute for my WordTrigger class, but that still leaves the problem of what variables I would be assigning the class instances to, because, in theory, I don't even know how long the list of triggers is, so I can't just create a static number of variables.

Is there any way, given a wordlist x numbers long, to create x number of variables and point them to a new instance of a class with a name extracted from the wordlist? I hope that makes sense.

user1427661
  • 11,158
  • 28
  • 90
  • 132

1 Answers1

4

use a dictionary:

dic={word:WordTrigger(parameters) for word in wordlist}

example:

>>> wordlist=['a','b','c','d','e']
>>> class A:
    def __init__(self,i):
        self.ind=i


>>> dic={word:A(i) for i,word in enumerate(wordlist)}
>>> dic['a'].ind
0
>>> dic['c'].ind
2
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • See [this article](http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html) for a discussion of why a dict is the right way to go. – Benjamin Hodgson Sep 25 '12 at 21:25