[Tutor] Classes

Sean 'Shaleh' Perry shalehperry@attbi.com
Tue Feb 25 21:19:02 2003


On Tuesday 25 February 2003 10:35, Timothy M. Brauch wrote:

> I think that might fix the problem.  I'm not sure the documentation mak=
es
> the distinction clear.  It is hard, especially if you are using a varia=
ble
> width font when reading, to distinguish between _ and __.  I'm not sure=
 how
> to notice this, other than doing what you did.  I can't think of any ot=
her
> examples, other than the 'special' functions like these, and as far as =
I
> know, all of them use 2 underscores.
>

2 underscores is the sign of "interpreter magic".  These all represent sp=
ecial=20
things Python does behind the scenes.  They are "hidden" in the sense tha=
t=20
you have to go out of the way to see them.

single underscores are reserved for the programmer.  If you have somethin=
g you=20
want kept back from public use this is the Python idiom.  Generally these=
=20
names are used for behind the scenes implementations.

class Random:
    def __init__(self, hardware): # do init stuff
        self.has_hardware =3D hardware

    def next(self): # returns the next random number from somewhere
        if self.has_hardware:       =20
            return self._real_random()

        return self._psuedo_random()

    def _real_random(self): # this will get a random number from hardware
        pass

    def _psuedo_random(self): # this will use some algorithm instead
        pass

r =3D Random(0) # use a psuedo random number generator

print "Chose this number just for you: %d" % r.next()

The two functions with leading underscores are not meant to be used by th=
e=20
user of the class they are just part of the implementation.