在所有类实例中检查布尔值

时间:2017-05-09 10:08:04

标签: python

我有一个模拟中的对象列表,它们以同步的方式在空间中移动。为了实现这一点,我创建了一个具有布尔值的类,一旦对象到达目的地,该类设置为true,并且等待每个对象完成,这样他们就可以一起开始下一个步骤。

class MyClass(object):
    def __init__(self, ID):
        self.ID = ID
        self.finished_condition = False

    def time_evolution(self, time_step):
        # Some method that updates the class instance over time, 

    def complete_check(self):
        # If the object is approximately at its finish point, as error
        # is allowed in position - set self.finished_condition to True

    def start_next_movement(self):
        # Some method called to begin the next leg:
        # called when all instances are finished.

object_list = [MyClass('1'), MyClass('2'), MyClass('3')]

while simulation_running == True:
    for k in object_list:
        k.time_evolution(0.05)
        k.complete_check()

    # If all finished_condition == True then call start_next_movement
    # for all instances of MyClass.

我已经将这些形成了一个类实例列表,我想检查所有对象是否已完成之前的移动步骤,以便我可以开始下一个。很明显,我可以检查是否已经完成了条件。在循环中是真的,但我想知道是否有更简洁的方法。

是否有一种简单的方法可以检查此类的每个实例的布尔值是否为真/假?

1 个答案:

答案 0 :(得分:0)

给定object_list = [MyClass('1'), MyClass('2'), MyClass('3')]

检查@Łukasz指出的all(o.finished_condition for o in object_list)之类的循环,或者重载:

class MyClass(object):
    def __init__(self, id_):
        self._id = id_
        self._finished_condition = False

    def __nonzero__(self):  # legacy Python2
        return self._finished_condition

    def __bool__(self):     # Python3
        return self._finished_condition

然后:all(object_list)