【发布时间】: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