"David" <da...@abbottdavid.com> wrote

have been attempting to learn about classes, this is my version, comments, suggestions always welcome.
-david

#!/usr/bin/python
from random import randrange
from sys import exit

class GuessNumber:
    def __init__(self):
        self.number = randrange(100)+1
        self.count_tries = 1
        self.total_tries = 5
    def update_count(self):
        self.count_tries += 1

This is a bad choice of class. It is a verb which is indicative
that its not an object. Objects are nearly always nouns.

You could use GuessableNumber.
Then it would have a number attribute which is the number
to guess. It could have a generate() ,method which produces
a new random number, possibly within a given range?

You could also add a compare method so you can compare
your guesses. The compare method could count the number
of calls and raise an exception if you compare more than N times.
(The value of N would be in the constructor.
Something like:

class GuessError(Exception): pass
class GuessedNumber:
    def __init__(self,tries=None,limits=None):...
    def generate(self, limits=None):...
    def __cmp__(self, aNumber):
          if self.count >= self.tries: raise GuessError
          ...

So I'd expect the client code to look like

target = GuessableNumber(tries=5, limits=(1,99)) # init calls generate internally
guess = int(raw_input('Guess-> '))
while True:
   try:
       if guess == target:
           print "Well done!"
           break
       else:
           guess = int(raw_input('Guess again-> '))
   except GuessError:
          print "Sorry, too many guesses, the number was", target.number


You could add another loop to ask if the player wanted to go again,
in which case you call target.generate() directly to reset the target.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to