Skip to content
Advertisement

Python, adding a different characteristic to each element of a list

i am currently working on a producion optimization tool. There are Jobs who needs to be produced on machines.

I want to add a workspeed for the machines so they can finish the jobs in a different speed depending on the machine it is processed on.

This is the class and list i am using for the machines:

number_of_machines = 3

class Machine(object):
    def __init__(self, workload, workspeed): 
        self.workload = workload
        self.workspeed = workspeed

all_machines =[] 
for i in range(number_of_machines):
    all_machines.append(Machine(0)) #puts the workload of all machines to 0 before the loop starts

i want to add a different float(for example 0.5 , 1.0 , 1.5) to each object in the list “all_machines”

Help would be very much appreciated!

Thanks in advance!

Advertisement

Answer

If you want workload to always have an initial value of 0 just define it in the class and remove the parameter from the __init__

class Machine(object):

    workload = 0

    def __init__(self, workspeed):
        self.workspeed = workspeed

If you want to keep __init__ with those two parameters you can use default value (notice the order of the parameters is reversed)

class Machine(object):

    def __init__(self, workspeed, workload=0):
        self.workload = workload
        self.workspeed = workspeed

For both options

all_machines = [Machine(0.5), Machine(1.0), Machine(1.5)]

for machine in all_machines:
    print(f'{machine.workload} {machine.workspeed}')

# output:
# 0, 0.5
# 0, 1.0
# 0, 1.5
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement