python:使用一个类来跟踪另一个类使用的数据

标签 python class

我正在通过书籍和互联网学习 Python。我正在尝试在单独的类(class)中记录游戏的分数。为了验证我的想法,我构建了一个简单的例子。由于某种原因,它看起来太复杂了。有没有更简单/更好/更 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)

最佳答案

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

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 类是一个异常(exception),因为您可能会向它添加更多代码。
  • 在 Python 中,类是用 CamelCase 编写的。全局常量通常以 UPPERCASE 编写。
  • raw_input() 返回一个字符串。 input() 返回评估为 Python 对象的字符串。

关于python:使用一个类来跟踪另一个类使用的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12015394/

相关文章:

python - 返回 send_file 的端点不再被调用

python - 将结构从 C++ 传递到 Python

c++ - 什么时候应该实现特定的构造函数?

python - 一个实例如何包含其他类的多个实例?

java - 我正在尝试使用具有随机位置的数组和类创建随机对象?

c++ - 如何在链表中搜索特定字符串并返回该值?

python - 正则表达式 : How to access multiple matches of a group?

python - 高效地在海量文件中搜索字符串

python - 将 win32lfn 扩展与 Mercurial 捆绑在一起

javascript - NodeJS 使用另一个文件中的类