Python-重置同一类的所有实例的值

时间:2019-01-06 17:00:59

标签: python class renpy

在我正在编写的Ren'Py游戏中,我正在尝试优化代码,而我一直坚持寻找一种方法来为同一类的所有实例重置相同的值。

这是我的代码:

init python:
    class Girl():
        def __init__(self,name,age):
            self.name = name
            self.age = age
            self.place = "Nowhere"
            self.appear = False

   Bree = Girl("Bree",26)
   Sasha = Girl("Sasha",27)

label reset_appear():
    Bree.appear = False
    Sasha.appear = False

目前,我只有该类的几个实例,但是我计划再增加50个,并且我想在继续之前解决该问题。

我想做这样的事情(还在上课的时候):

def reset_appear(self):
    self.appear = False

但是您仍然需要为每个实例调用它。我还想到了类之外的相同功能,但我不知道如何编写代码。

2 个答案:

答案 0 :(得分:1)

您可以使用class属性存储所有实例和classmethod 遍历所有实例:

class Girl:
    _instances = []
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.place = "Nowhere"
        self.appear = False
        self._instances.append(self)

    @classmethod
    def reset_appear(cls):
        for instance in cls._instances:
            instance.appear = False

    def __repr__(self):
        # added for sake of example
        return '{} {}'.format(self.name, self.appear)


Bree = Girl("Bree", 26)
Bree.appear = True
Sasha = Girl("Sasha", 27)
Girl.reset_appear()
print(Girl._instances)
#  [Bree False, Sasha False]

答案 1 :(得分:0)

我对Ren'Py不熟悉,所以我的示例使用的是普通Python。

您需要在某个地方收集Girl类的所有实例。 这可以是简单列表:

class Girl():
    def __init__(self,name,age):
        self.name = name
        self.age = age
        self.place = "Nowhere"
        self.appear = False

Bree = Girl("Bree", 26)
Sasha = Girl("Sasha", 27)
girls = [Bree, Sasha]

for girl in girls:
    girl.appear = False

或者您可以让类来处理它:

class Girl():
    instances = []

    def __init__(self,name,age):
        Girl.instances.append(self)
        self.name = name
        self.age = age
        self.place = "Nowhere"
        self.appear = False

for girl in Girl.instances:
    girl.appear = False