1

I'm creating several instances of a class (Workers) with a method (remaining_time). Some workers work on the same task, so the remaining_time method needs to know these workers to calculate the right time. Is there a pythonic way to keep references to class members, so that I could access all instances or specific variables of instances?

If Workers was also a list with all instances in it, the code would look like this:

class Workers:
    def __init__(self, task, working_power):
        self.task = task
        self.working_power = working_power
    def remaining_time(self, task):
        working_power = sum([x.working_power for x in Workers if x.task = self.task])
        time = self.task.time/working_power

The only way I found to have a list like that is using a default value empty list, that is shared between all instances:

def __init__(self, task, working_power, instances = []):
    self.task = task
    self.working_power = working_power
    instances.append(self)

That does not seem to be elegant though.

Thank you!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
pan
  • 15
  • 2

1 Answers1

0

Usual way is a class variable:

class Workers:
    instances = []

    def __init__(self, task, working_power):
        self.task = task
        self.working_power = working_power
        Workers.instances.append(self)

    def remaining_time(self, task):
        working_power = sum([x.working_power for x in Workers.instances if x.task = self.task])
        time = self.task.time/working_power
Michael Butscher
  • 10,028
  • 4
  • 24
  • 25