views:

606

answers:

2

I've got a piece of code which contains a for loop to draw things from an XML file;

   for evoNode in node.getElementsByTagName('evolution'):
      evoName    = getText(evoNode.getElementsByTagName(        "type")[0].childNodes)
      evoId      = getText(evoNode.getElementsByTagName(      "typeid")[0].childNodes)
      evoLevel   = getText(evoNode.getElementsByTagName(       "level")[0].childNodes)
      evoCost    = getText(evoNode.getElementsByTagName("costperlevel")[0].childNodes)

      evolutions.append("%s x %s" % (evoLevel, evoName))

Currently it outputs into a list called evolutions as it says in the last line of that code, for this and several other for functions with very similar functionality I need it to output into a class instead.

class evolutions:
    def __init__(self, evoName, evoId, evoLevel, evoCost)
        self.evoName = evoName
        self.evoId = evoId
        self.evoLevel = evoLevel
        self.evoCost = evoCost

How to create a series of instances of this class, each of which is a response from that for function? Or what is a core practical solution? This one doesn't really need the class but one of the others really does.

+4  A: 
for evoNode in node.getElementsByTagName('evolution'):
  evoName      = getText(evoNode.getElementsByTagName("type")[0].childNodes)
  evoId      = getText(evoNode.getElementsByTagName("typeid")[0].childNodes)
  evoLevel   = getText(evoNode.getElementsByTagName("level")[0].childNodes)
  evoCost      = getText(evoNode.getElementsByTagName("costperlevel")[0].childNodes)

  temporaryEvo = Evolutions(evoName, evoId, evoLevel, evoCost)
  evolutionList.append(temporaryEvo)

  # Or you can go with the 1 liner
  evolutionList.append(Evolutions(evoName, evoId, evoLevel, evoCost))

I renamed your list because it shared the same name as your class and was confusing.

Teifion
Could you also rename their class to be Uppercase, like Proper Class Names Should Be?
S.Lott
I thought that was just me that put classes as Uppercase for the first letter. Or do you mean all letters?
Teifion
+4  A: 

A list comprehension might be a little cleaner. I'd also move the parsing logic to the constructor to clean up the implemenation:

class Evolution:
    def __init__(self, node):
        self.node = node
        self.type = property("type")
        self.typeid = property("typeid")
        self.level = property("level")
        self.costperlevel = property("costperlevel")
    def property(self, prop):
        return getText(self.node.getElementsByTagName(prop)[0].childNodes)

evolutionList = [Evolution(evoNode) for evoNode in node.getElementsByTagName('evolution')]

Alternatively, you could use map:

evolutionList = map(Evolution, node.getElementsByTagName('evolution'))
Jorenko
`property` is a built-in function in Python. It is a bad style to use it the way you did. http://docs.python.org/library/functions.html#property
J.F. Sebastian