3

我正在通过书籍和互联网学习 Python。我正在尝试在单独的课程中保持游戏得分。为了测试我的想法,我构建了一个简单的例子。由于某种原因,它看起来太复杂了。有没有更简单/更好/更 Pythonic 的方式来做到这一点?

我的代码如下:

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

2 回答 2

1

这是我将如何格式化您的代码:

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)

还有一些提示:

  • 我不会创建一个只包含执行一项特定任务的代码的新类。如果该类不接受参数或不简化您的代码,请不要创建它。但是,您的Game类是一个例外,因为您可能会向它添加更多代码。
  • 在 Python 中,类是用CamelCase. 全局常量通常用UPPERCASE.
  • raw_input()返回一个字符串。input()返回评估为 Python 对象的字符串。
于 2012-08-18T02:50:30.327 回答
0

我以更好的方式问了这个问题,并在这里得到了我想要的东西:

python:如何在不更改参数的情况下调用函数?

于 2012-08-21T16:15:27.170 回答