如何在python中创建和保持一组变量?

2024-06-02 15:27:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个应用程序,用一组变量读取电报输入的消息,然后与用户开始一个游戏。所以我创建了一个类来表示游戏的一个实例,使得每次聊天都可以玩一个游戏:

class Battle:
    def __init__(self, mainchat):
        self.mainchat = mainchat
        print('Instance of battle started on chat %s' % self.mainchat)
    pcount = 0
    team1 = []
    team2 = []
    p1 = ()
    p2 = ()
    p1score = 0
    p2score = 0
    battlechoicep1 = -1
    battlechoicep2 = -1

所以,当我收到一条消息时,我就开始基于用户输入的一个战斗实例,例如

battle = Battle(chat_id)
battle.p1 = 'Paul'
battle.battlechoicep1 = 4
...

这种方法现在运行得很好,但是每次我想重置战斗时,我都会通过一个函数来执行以下操作:

    battle.pcount = 0
    battle.team1 = []
    battle.team2 = []
    battle.p1 = ()
    battle.p2 = ()
    battle.p1score = 0
    battle.p2score = 0
    battle.battlechoicep1 = -1
    battle.battlechoicep2 = -1
    save() # outside function that saves the scores into a pickle file
    return

所以,我想让它成为我类中的一个函数,所以每次我调用战斗.重置它会叫这样的东西

def reset():
    battle.pcount = 0
    battle.team1 = []
    battle.team2 = []
    battle.p1 = ()
    battle.p2 = ()
    battle.p1score = 0
    battle.p2score = 0
    battle.battlechoicep1 = -1
    battle.battlechoicep2 = -1
    save() # outside function that saves the scores into a pickle file
    return

我不知道如何正确处理这个问题,我甚至不知道我到目前为止所做的是否是“正确的”(至少它是有效的)。 在类中创建函数(比如def reset(self):)似乎没有效果。你知道吗


Tags: 函数self游戏defp2p1battleteam1
2条回答

你在正确的轨道上与def reset(self)。您只需要在方法本身中将battle的实例更改为self注意:这需要是Battle类的方法。你知道吗

def reset(self):
    self.pcount = 0
    ... # etc
    save() # outside function that saves the scores into a pickle file

当您传入self作为类方法的第一个参数时,它允许该方法处理您调用它的类的实例。如果只执行def reset(self),而不将battle更改为self,它将尝试修改当前范围中名为battle的变量,在本例中,该变量可能不存在。你知道吗

如果您只想reset创建一个全新的对象而不保留任何属性,您可以做的另一件事是:

def reset(self):
    return Battle()

你就快到了!你知道吗

class Battle:
    def __init__(self, mainchat):
        self.mainchat = mainchat
        print('Instance of battle started on chat %s' % self.mainchat)
        self.reset()

    def reset(self):
        self.team1, self.team2 = [], []
        self.p1 = self.p2 = ()  #New tuples will be assigned and overwritten
        self.pcount = self.p1score = self.p2score = 0
        self.battlechoicep1 = self.battlechoicep2 = -1
        save() # outside function that saves the scores into a pickle file

所以当您需要重置时,只需调用battle.reset()!也许save函数也可以是类方法,只要遵循相同的格式即可。你知道吗

相关问题 更多 >