[Tutor] Understanding Object oriented programming with Python

Alan Gauld alan.gauld at yahoo.co.uk
Fri Sep 4 19:11:33 EDT 2020


On 04/09/2020 23:43, Alan Gauld via Tutor wrote:

Following up on my own post I notice a couple of other
points I should have picked up...

> As for the initializer would it not be much more convenient to allow the
> user to pass the number as an argument to init()? Then you can calculate
> the value when first initialised.
> 
> def __init__(self, number = none):
>     if number:
>        self.number = number
>        self.value = self.calculate()
>     else:
>        self.number = None
>        self.value = None

Since we decided we would have a setnum() method
we should use it here rather than duplicate code.
And since we don;t want users setting the data
explicitly we should indicate that with our
naming convention:

self.__num  and self.__value

so the init should be:

def __init__(self,number = None):
    if number:
       self.setnum(number)
    else:
       self.__number = None
       self.__value = None


> def setnum(self, num):
>     if num == self.number: return
>     self.num = num
>     self.calculate()

This would be a good place to check that the number
is valid for a factorial - ie non-negative. Classes should
try to ensure that bad data never gets into the class,
that's a powerful tool in preventing obscure bugs.
So setnum should be:

def setnum(self, num):
    if num < 0: raise ValueError
    if num == self.__number: return
    self.__number = num
    self.calculate()


-- 
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