简体   繁体   中英

How to instantiate and populate class variables using a list?

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?

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?

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM