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

Phe*_*ano 2 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
Run Code Online (Sandbox Code Playgroud)

所以,一旦我收到消息,我就会根据用户输入启动一个战斗实例,例如

battle = Battle(chat_id)
battle.p1 = 'Paul'
battle.battlechoicep1 = 4
...
Run Code Online (Sandbox Code Playgroud)

这种方式现在一直很好,但每次我想重置战斗时,我都会通过一个函数执行此操作:

    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
Run Code Online (Sandbox Code Playgroud)

所以,我想这样做,所以这是我班上的一个函数,所以每次我调用battle.reset它会调用这样的东西

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
Run Code Online (Sandbox Code Playgroud)

我不知道如何正确处理这个问题,我甚至不知道我到目前为止所做的事情是否"正确"(它至少起作用).在类中创建函数(如def reset(self):)似乎没有任何效果.

Mor*_*app 5

你正走在正确的轨道上def reset(self).你只需要的情况下更改battleself方法本身.注意:这需要是Battle该类的方法.

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

当您self作为类方法的第一个参数传入时,它允许该方法处理您调用它的类的实例.如果您只是在def reset(self)不更改battleto的情况下self,它将尝试修改当前调用范围中的变量battle,在这种情况下可能不存在.

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

def reset(self):
    return Battle()
Run Code Online (Sandbox Code Playgroud)

  • 我想知道`save()`是否应该是`save(self)`很难知道`save`是什么 (2认同)