0

Python 3.4.2 question, I have extensively looked for an answer to this, cannot find it.

I am trying to create python objects (or whatever you would call lists, dicts, and classe/object instantiations) by assigning strings to the definition. Or put differently, I want to use strings on the left hand side of the assign equation.

For instance, if we have a class, and an assignment/instantiation:

class char_info:
    def __init__(self):
        self.name           = 'Joe'
        self.mesh           = 'Suzanne'
newchar = char_info()
print (newchar.name)

Joe

I would like to use using a string from another source (say a list) as the instantiated name, instead of "newchar". However, I am not sure the syntax. I need to reference this string on the left hand side of the equation. Furthermore, how do I reference this in later code since I wouldn't know the name beforehand, only at runtime?

Obviously this doesn't work:

list = ['Bob', 'Carol', 'Sam']
# list[0] = char_info() #this doesn't work, it would
# try assigning the value of char_info() to the item in [0] 
str(list[0]) = char_info()   #also doesn't work, obviously
print (str(list[0]) #obviously this is wrong, but how do you reference?

location: :-1

Error: File "\Text", line 2

SyntaxError: can't assign to function call

What I want is to have say, a loop that iterates over a list/dict and uses those strings to instantiate the class. Is there any way to do this? Special syntax I am not aware of?

By the way, this same thing should be the solution to do the same thing with creating list names, dict names, etc. Heck, even something simple like enumerating a variable name or assigning variables out of a list. How do you dynamically define the assignment name?

Cœur
  • 37,241
  • 25
  • 195
  • 267
J Rowoldt
  • 111
  • 3

2 Answers2

-1

You can use exec i.e. exec(list[0] + "=char_info()") but this is a bad idea. Using a dictionary is better:

 chars = {}
 chars[list[0]] = char_info()
miyamoto
  • 1,540
  • 10
  • 16
-1

What I want is to have say, a loop that iterates over a list/dict and uses those strings to instantiate the class. Is there any way to do this?

class char_info:
    def __init__(self, name):
        self.name           = name

list_names = ['Bob', 'Carol', 'Sam']
list_char_info = [char_info(name) for name in list_names]

The above code will instantiate a class for each name in the list of names

Alter
  • 3,332
  • 4
  • 31
  • 56
  • I agree with the others, a dictionary is best – Alter Jul 07 '16 at 22:44
  • `exec` is just as bad as `eval` and not necessary here. – TigerhawkT3 Jul 07 '16 at 22:52
  • True enough. I changed my answer to only answer the main question. exec() was never a good solution, but it did solve `I want to use strings on the left hand side of the assign equation.` and ` I need to reference this string on the left hand side of the equation.` – Alter Jul 07 '16 at 23:18