Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: using a class to keep track of data used by another class

Tags:

python

class

I'm learning Python via book and internet. I'm trying to keep score of a game in a separate class. In order to test my idea, i've constructed a simple example. It looks too complicated for some reason. Is there a simpler/better/more Pythonic way to do this?

My code is as follows:

import os

class FOO():
    def __init__(self):
        pass

    def account(self, begin, change):
        end = float(begin) + float(change)
        return (change, end)        

class GAME():
    def __init_(self):
        pass

    def play(self, end, game_start):
        os.system("clear")
        self.foo = FOO()

        print "What is the delta?"
        change = raw_input('> ')

        if game_start == 0:
            print "What is the start?"
            begin = raw_input('> ')
        else:
            begin = end

        change, end = self.foo.account(begin, change)
        print "change = %r" % change
        print "end = %r" % end

        print "Hit enter to continue."
        raw_input('> ')

        self.play_again(end, game_start)    

    def play_again(self, end, game_start):

        print "Would you like to play again?"
        a = raw_input('> ')
        if a == 'yes':
            game_start = 1
            self.play(end, game_start)
        else: 
            print "no"
            exit(0)

game = GAME()
game.play(0, 0)
like image 638
DBWeinstein Avatar asked Mar 27 '26 02:03

DBWeinstein


1 Answers

Here's how I would format your code:

import os

class Game(object):
    def play(self, end, game_start=None):
        os.system("clear")

        change = input('What is the delta? ')

        # Shorthand for begin = game_start if game_start else end
        begin = game_start or end
        end = float(begin + change)  

        print "change = {}".format(change)
        print "end = {}".format(end)

        self.play_again(end, game_start)    

    def play_again(self, end, game_start):
        raw_input('Hit enter to continue.')

        if raw_input('Would you like to play again? ').lower() in ['yes', 'y']:
            self.play(end, game_start)
        else:
            exit(0)

if __name__ == '__main__':
    game = Game()
    game.play(0, 0)

And a few tips:

  • I wouldn't create a new class that contains only code to perform one specific task. If the class doesn't take arguments or doesn't simplify your code, don't create it. Your Game class is an exception, however, as you would probably add more code to it.
  • In Python, classes are written in CamelCase. Global constants are usually written in UPPERCASE.
  • raw_input() returns a string. input() returns the string evaluated into a Python object.
like image 112
Blender Avatar answered Mar 29 '26 16:03

Blender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!