I would like to instantiate variables within a class using a list. This is what I am trying to achieve:
my_list = ['apple', 'banana', 'mango']
my_object = my_class(my_list)
vars(my_object) => {'apple': 'apple', 'banana': 'banana', 'mango': 'mango'}
my_list = ['pear', 'melon']
my_object = my_class(my_list)
vars(my_object) => {'pear': 'pear', 'melon': 'melon'}
Is there any method to automatically instantiate variables using list which might not be known at the time I write the code for the class?
CodePudding user response:
You could do
class MyClass:
def __init__(self, _list):
for value in _list:
setattr(self, value, value)
But you should not do this, what is your use case ?
CodePudding user response:
I could get no further than this code:
my_list = ["apple", "banana", "mango"]
class my_class:
def __init__(self, my_list: list) -> None:
pass
my_object = type("my_class", (), {k: k for k in my_list})
print(vars(my_object))