ben Heo ben Heo - 7 months ago 15
Python Question

Python - creating a struct with '.' from an array of strings

I am new to python and wondering if how I can create data struct using '.'
For example, given an array of strings,

mystr=['aaa', 'bbb', 'ccc']
commonstr = 'zzz'

for str in mystr
# something like creating '.' struct
self = __create_dot_struct_with_value__(self, str, str+commonstr)


So the result will look like

self.aaa = 'aaazzz'
self.bbb = 'bbbzzz'
self.ccc = 'ccczzz'


How can I do this?
Thanks!

Answer

Use setattr:

class x(object):
    pass

for item in mystr:
    setattr(x, item, item + commonstr)

Now you can do things like x.aaa, and have it return aaazzz.

setattr lets you add object attributes dynamically. I would be very wary of using it inside an existing class unless you're absolutely sure it won't mess up the rest of your class, but if you just want a dummy class, this is a good way to do it.