ben Heo ben Heo - 2 years ago 85
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 = 'aaazzz'
self.bbb = 'bbbzzz'
self.ccc = 'ccczzz'

How can I do this?

Answer Source

Use setattr:

class x(object):

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

Now you can do things like, 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download