[Tutor] Class Tips

Alan Gauld alan.gauld at btinternet.com
Sun May 31 02:15:20 CEST 2009

"David" <david at abbottdavid.com> wrote

>I took this program that determines a fertilizer application rate;
> ...
> And converted it to class/object to learn how they work. Just looking 
> for some pointers, if I did it correctly etc.

For such a small program its hard to see what else you could have 
done. Technically itys not too bad, I've made a couple of suggestions 
below. However, leaving the fact that its an excercise I'd say that 
really this is just a function rather than a class.

> class FertRate:
>     def __init__(self, rate, nitrogen, acre, bag):
>         self.area = 43.560
>         self.app = rate / (nitrogen / 100.00)
>         self.acre = acre
>         self.bag = bag
>     def result(self):
>         result = self.app * self.area * self.acre / self.bag
>         print 'You should apply %0.2f bags.' % result

Its never a good idea to include printing in the same function 
as calculation. IT would be better to have two functions one to 
calculate and one to generate the printable output. (The actual 
printing is best done outside the class altogether, it improves 
the reusability. For example prints don't work in a GUI but 
a formatted string can be used.

But even if you keep it as one function at lest return the result 
as a string rather than print it

> def main():
>     rate, nitrogen, acre, bag = get_inputs()
>     frate = FertRate(rate, nitrogen, acre, bag)

This could have just been:

frate = FertRate( get_inputs() )

which saves the need for the variables.

>     frate.result()

So if you took my advice about returning a string this becomes

print frate.result()

But as I say you could just have made FertRate a function:

print FertRate( get_inputs() )

and it would have been just as effective, classes really 
only start to be useful on slightly larger programs than this.

But as an example of using a class its nearly OK, just the 
tweak of the return value to think about - and that applies 
to the function version too!

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list