Dynamic Class Creation
Chris Rebert
clp2 at rebertia.com
Tue Mar 16 12:53:37 EDT 2010
On Tue, Mar 16, 2010 at 9:49 AM, Jack Diederich <jackdied at gmail.com> wrote:
> On Tue, Mar 16, 2010 at 2:18 AM, Chris Rebert <clp2 at rebertia.com> wrote:
>> On Mon, Mar 15, 2010 at 11:01 PM, Josh English
>> <joshua.r.english at gmail.com> wrote:
<snip>
>>> What's the best way to create these helper methods?
>
> You can either define a catch-all __getattr__ method to look them up
> dynamically, or as Chris kinda-suggested write descriptors for the
> individual elements.
>
> class Market():
> def __init__(self, elem):
> self._elem = elem
> def __getattr__(self, name):
> try:
> # I'm assuming this raises a KeyError when not found
> return self._elem.get(name)
> except KeyError:
> return self._elem.find(name)
> def __setitem__(self, name, value):
did you mean __setattr__ here?
<snip>
> The getattr/setattr method is easier to understand and will handle
> arbitrary elements; for the descriptors version you'll have to define
> one for each tag that might be used on the class.
Cheers,
Chris
--
http://blog.rebertia.com
More information about the Python-list
mailing list