[Tutor] Need all values from while loop - only receiving one
alan.gauld at yahoo.co.uk
Sat Jul 7 17:35:39 EDT 2018
On 07/07/18 18:46, Daryl Heppner wrote:
> I'm stepping back to simply return the DealID from the XML using the
> concept of a class. My code results in exit code 0 but doesn't print
> any results. Could you give me a hint where I'm missing something?
You have an issue which has shown up in several of the code
samples you have sent in that you don't assign values to variables.
In your code below Deal is a class. To use it you must create an
instance, which you do at the bottom.
But the methods defined in the class do not execute until
you call them from the instance. So in your code below you
create an instance, but because it is not stored anywhere
(with a variable) you do not execute any of its methods
(except init) and Python, seeing that it is unassigned,
immediately deletes the object. To use an object you must
store it someplace; either by assigning it to a variable
or inserting it into some kind of collection
> root = tree.getroot()
> class Deal:
> def __init__(self, rt):
> for deal in rt.findall("Deals/Deal"):
> self.dealID = deal.get("DealID")
> def __str__(self):
> return self.dealID
You only need the iter/next stuff if you are creating an
iterator which usually means a collection of some kind.
Since your class only represents one deal object you almost
certainly don't need iter/next and they just add confusion.
You can add them back in later if you find you do need them.
This line should look like:
testDeal = Deal(root)
Which should print the DealId via the __str__() method which
is called implicitly by the print() function.
However, there is one other issue that I think you need
to address. You call findall() which implies that it returns
some kind of collection of deals, not just one.
You are iterating over that list assigning self.DealID
each time. That means that you are only storing the last ID.
For testing things you can probably just go with the first
one, like so:
allDeals = rt.findall("Deals/Deal"):
self.dealID = allDeals.get("DealID")
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:
More information about the Tutor