如何避免全局变量(和使用类?)Python

时间:2019-06-10 11:11:49

标签: python class variables global

进行一些学习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()

当前它可以与我的全局变量一起使用,但是我认为这不是“正确”的方法。

1 个答案:

答案 0 :(得分: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。