[Tutor] Error in class definition of __init__
Peter Otten
__peter__ at web.de
Thu Feb 15 04:12:53 EST 2018
Leo Silver wrote:
> Hello.
>
> I'm trying to create a class to represent products which includes a list
> of volume based pricing and sets the first of these as the unit price:
>
> def __init__(self, RatePlanID):
> self.id = RatePlanID
> self.name = RatePlans.toggleids[self.id]
> self.pricing = RatePlans.pricebreaks[self.name]
To debug your code print out the list and a few other things here with:
print("name:", self.name)
print("price breaks:", RatePlans.pricebreaks)
print("pricebreaks[name]:", RatePlans.pricebreaks[self.name])
> self.unitprice = RatePlans.pricebreaks[self.name][0]
>
> This code gives an IndexError:
> ...
> self.unitprice = RatePlans.pricebreaks[self.name][0]
> IndexError: list index out of range
>
> However, the same code with the last line changed to:
> self.unitprice = RatePlans.pricebreaks[self.name][:1]
Slicing allows for the list to be shorter than specified:
>>> items = [1, 2, 3]
>>> items[:1]
[1]
>>> items[:100]
[1, 2, 3]
In your case it's an empty list:
>>> items = []
>>> items[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> items[:1]
[]
>
> seems to work OK, although, I can't process it further and extract the
> second element of the pair.
>
> The list I'm trying to process is:
> [(1, 21.0), (100, 19.6), (250, 18.4), (500, 17.6), (1000, 16.7), (2500,
> 14.7), (10000, 13.7)]
I'm pretty sure that's not what you'll see printed if you follow my advice
and add those print() calls above.
> and a cut and paste into the IDLE GUI let's me process it exactly as I
> expect (including picking the second element of the tuple, the price
> rather than the volume level):
>>>> [(1, 21.0), (100, 19.6), (250, 18.4), (500, 17.6), (1000, 16.7), (2500,
> 14.7), (10000, 13.7)][0][1]
> 21.0
>
> What am I missing about the class definition that won't let me put this
> class in the init call?
This has nothing to do with __init__() specifically.
More information about the Tutor
mailing list