Dynamic Class Creation

Josh English joshua.r.english at gmail.com
Tue Mar 16 07:01:07 CET 2010

I have a large program with lots of data stored in XML. I'm upgrading
my GUI to use ObjectListView, but with my data in XML, I don't have
regular objects to interact with the OLV. I do have an XML validator
that defines the structure of the XML elements, and I'm trying to
dynamically create a class to wrap the XML element.

So, an element like:

<market code="WotF">
<title>Writers of the Future</title>

I want to create a class like:

class Market(object):
    def __init__(self, elem):
        self._elem = elem

    def get_code(self):
        return self._elem.get('code')

    def set_code(self, value):
        self._elem.set('code', value)

    def get_title(self):
        return self._elem.find('title').text

    def set_title(self, value):
        node = self._elem.find('title')
        node.text = value

Naturally, I don't want to hand code this for every interface but
would like to create them dynamically. (The laziness of programming, I

I have tried several solutions that I found on various forums, but
they are all several years old.


What's the best way to create these helper methods?

How can I attach them to the class and have it run?

I have had a few solutions work where I had a class with three methods
(get_code, get_tier, get_mail) but they all return the same value, not
the individual values.

Josh English

More information about the Python-list mailing list