简体   繁体   中英

python dynamically create attributes class

I am facing issues adding class attributes dynamically from a list of strings, consider the following scenario:

This is my class:

class Customer(object):
    def __init__(self,**kw):
        self.__dict__ = kw

    def add_attributes(self,**kw):
        self.__dict__.update(kw)  

#a group of attributes i want to associate with the class
list = []
list.append("name")
list.append("age")
list.append("gender")

Customer c

for i in list:
    # i is the attribute name for the class
    c.add_attributes( i = "test")

The issue seems to be the fact that it is treating the attribute name as a string, can someone please advise

i = "test" is actually converted to {'i':'test'} when passed to **kwargs inside add_attributes , so you need to do something like this:

for i in my_list:
    c.add_attributes(**{ i : "test"})

Instead of directly updating __dict__, you can use the setattr builtin method:

for i in list:
    # i is the attribute name for the class
    setattr(c, i, "test")

In my opinion, playing with internal attributes should be the last resort.

Instead of a for-loop, you could use dict.fromkeys :

c.add_attributes(**dict.fromkeys(seq, "test"))

since

In [13]: dict.fromkeys(seq, "test")
Out[13]: {'age': 'test', 'gender': 'test', 'name': 'test'}

The ** tells Python to unpack the dict into keyword arguments. The syntax is explained here and in the docs, here .


By the way, it's best not to use list as a variable name, since it makes it difficult to access the builtin of the same name.

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