【问题标题】:How to avoid globals (and use classes)?如何避免全局变量(并使用类)?
【发布时间】:2019-06-10 11:11:49
【问题描述】:

在学习 Python,尤其是面向对象编程方面进行一些练习。我正在创建一个简单的基于文本的游戏。我在使用全局变量方面有点挣扎。人们说最好避开它们。

我的问题是如何在没有它们的情况下使事情正常工作以及在哪里声明这些变量。

目前,在我的 main() 方法中,我将根据游戏中可能发生的每个房间或交互的类来启动游戏。 但是有一些我想随时访问的对象,比如敌人或主角,比如健康、库存等(见代码)。

我从这些变量创建了一个全局变量以随时访问它,但我认为我不应该这样做。

有什么建议我应该怎么做?

class Character(object):

    def __init__(self, location, accuracy):
            self.current_health = 100
        self.max_health = 100
        self.max_ammo = 20
        # self.current_ammo = 0
        self.current_ammo = 20
        # self.inventory = {}
        self.inventory = {'Gun': True}
        self.location = location
        self.accuracy = accuracy


class MainCharacter(Character):
    # some extra attributes only for the main character


class EnemyChar(Character):

    def __init__(self, location, accuracy, can_see_you=True):
        self.type = 'Alien'
        self.can_see_you = can_see_you
        super(EnemyChar, self).__init__(location, accuracy)


def main():
    # Some globals to be able to access anytime
    global enemies, main_char, keypad


    # Where we start
    first_room = 'first_room'

    # Enemies
    enemies = {
        #'Enemy_1': EnemyChar('small_ally', 30, False),
        'Enemy_1': EnemyChar(first_room, 30, False),
        'Enemy_2': EnemyChar(first_room, 90)
    }

    # You
    main_char = MainCharacter(first_room, 50)

    # Stuff to interact with
    keypad = Keypad()

    map = Map(first_room)
    game = GameEngine(map)
    game.play()


if __name__ == '__main__':
    main()

目前它适用于我的全局变量,但我认为这不是“正确”的做法。

【问题讨论】:

    标签: python class variables global


    【解决方案1】:

    这通常通过使用一些全局类作为所有这些变量的容器来解决。例如:

    class Game:
        def __init__(self):
            # Where we start
            self.first_room = 'first_room'
    
            # Enemies
            self.enemies = {
                #'Enemy_1': EnemyChar('small_ally', 30, False),
                'Enemy_1': EnemyChar(self.first_room, 30, False),
                'Enemy_2': EnemyChar(self.first_room, 90)
            }
    
            # You
            self.main_char = MainCharacter(self.first_room, 50)
    
            # Stuff to interact with
            self.keypad = Keypad()
    
            self.map = Map(self.first_room)
            self.game = GameEngine(map)
    
        def play(self):
            self.game.play()
    

    等等。现在,当您需要其中一个变量时,您可以创建接受 Game 对象的函数,或者使该函数成为 Game 类的方法。在您的情况下,您可能可以使用 GameEngine 而不是 Game。

    【讨论】:

    • 非常感谢您的回答!因此,如果我理解正确,我可以在我的 GameEngine 类中创建 self.x 变量。在我的 play() 方法中,我可以在每次从房间切换时发布“self”变量:python def play(self): current_scene = self.first_room while True: next_scene = current_scene.enter(self) etc...
    • 是的。您可以使用 GameEngine 或创建另一个类,这取决于很多因素,很难判断。
    猜你喜欢
    • 2015-12-26
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 2012-05-04
    • 2016-03-19
    • 2012-02-02
    • 2020-09-02
    • 2022-01-22
    相关资源
    最近更新 更多