python - Instantiate a class using a variable for its name -
this question has answer here:
i'm little new python, , hoping might able me problem i've got.
i have need instantiate multiple objects using variables in list. let's have list of 2 items, ["apple", "orange"] , want use theses names instantiated class based on class fruit, end 2 objects, apple , orange of class fruit.
i've tried doing can't seem figure out how use variable name name of instantiated class. code doesn't work, might give idea i'm trying achieve:
class fruit: pass my_list = ["apple", "orange"] item in my_list: item = fruit() type(apple)
this doesn't work hope gives idea i'm trying achieve. error:
nameerror: name 'apple' not defined
what see is:
>>> type(apple) <type 'instance'>
any pointers can offer appreciated :)
thanks!
dynamically creating variables not idea. use dictionary instead:
>>> fruits = {} >>> item in my_list: ... fruits[item] = fruit() ... >>> [(k, type(v)) k, v in fruits.items()] [('orange', <class '__main__.fruit'>), ('apple', <class '__main__.fruit'>)]
i suppose similar thing in global scope playing globals()
, consider bad practice.
Comments
Post a Comment