当前位置: 动力学知识库 > 问答 > 编程问答 >

python: using a class to keep track of data used by another 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)

网友答案:

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.
网友答案:

I asked the question a better way and got what I was looking for here:

python: how do I call a function without changing an argument?

分享给朋友:
您可能感兴趣的文章:
随机阅读: