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?