[Tutor] Class Inheritance

Alan Gauld alan.gauld at yahoo.co.uk
Tue Feb 21 05:23:33 EST 2017


On 21/02/17 09:49, Rafael Knuth wrote:

> class FullPriceCustomer(object):
>     def __init__(self, customer, rate, hours):
> 
> 
> class DiscountCustomer(FullPriceCustomer):
>     discount = 0.7
>     def calculate_discount(self, rate, hours):
> 
> customer_one = DiscountCustomer("Customer A", 75, 100)
> customer_two = FullPriceCustomer("Customer B", 75, 100)

You create two instances and as such the
FullPriceCustomer.__init__() method gets
executed in both cases. This is because
the subclass does not provide an __init__()
of its own, so the inherited one is used.

Your discount is calculated in the
calculate_discount() method, but that is
never called. If you added a line:

customer_one.calculate_discount(75,100)

you would see the discount appear.

Alternatively create an init() for your
subclass that calls the superclass init()
then calls

self.calculate_discount(rate,hours)

BTW It's bad practice to mix calculations
and display(print) in the same method,
it's better to separate them, but
that's probably a topic for another thread
Get the inheritance sorted first :-)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list