On 10/28/2011 08:48 AM, DevPlayer wrote:
On Oct 27, 3:59 pm, Andy Dingley<ding...@codesmiths.com> wrote:
I have some XML, with a variable and somewhat unknown structure. I'd
like to encapsulate this in a Python class and expose the text of the
elements within as properties.
How can I dynamically generate properties (or methods) and add them to
my class? I can easily produce a dictionary of the required element
names and their text values, but how do I create new properties at run
time?
Thanks,
class MyX(object):
pass
myx = myx()
xml_tag = parse( file.readline() )
# should be a valid python named-reference syntax,
# although any object that can be a valid dict key is allowed.
# generally valid python named reference would be the answer to
your question
attribute = validate( xml_tag )
# dynamicly named property
setattr( myx, attribute, property(get_func, set_func, del_func,
attr_doc) )
# "dynamicly named method"
# really should be a valid python named-reference syntax
myfunc_name = validate(myfunc_name)
def somefunc(x):
return x+x
# or
somefunc = lambda x: x + x
setattr( myx, myfunc_name, somefunc )
So beaware of:
# \\\\\\\\\\\\\\\\\\\\\\\\\
setattr(myx, '1', 'one')
myx.1
File "<input>", line 1
x.1
^
SyntaxError: invalid syntax
# \\\\\\\\\\\\\\\\\\\\\\\\\
x.'1'
File "<input>", line 1
x.'1'
^
SyntaxError: invalid syntax
# \\\\\\\\\\\\\\\\\\\\\\\\\
x.__dict__['1'] # returns
'one'
x.__dict__ # returns
{'1': 'one'}
So you should validate your variable names if you are getting them
from somewhere.
XML does not allow attribute names to start with a number, so I doubt
you need to worry about that. In addition, if you also need to
dynamically access attributes and you have zero control of the name, you
can use getattr().
--
http://mail.python.org/mailman/listinfo/python-list