Here's my example code:
#!/usr/bin/env python3
LIST_OF_UNITS = {}
class Unit():
def __init__(self,name, value):
self.name = name
self.value = value
def create_new_unit(name, value):
return Unit(name, value)
def add_new_unit(d, name, value):
d[name] = Unit(name, value)
return d
unit = create_new_unit('reactor1', 1)
LIST_OF_UNITS[unit.name] = unit
unit = create_new_unit('reactor2', 2)
LIST_OF_UNITS[unit.name] = unit
LIST_OF_UNITS = add_new_unit(LIST_OF_UNITS, 'reactor3', 3)
print(LIST_OF_UNITS)
LIST_OF_UNITS = add_new_unit(LIST_OF_UNITS, 'reactor3', 4)
print(LIST_OF_UNITS)
As you can see I have two ways of adding objects to the dictionary. Not yet sure which is the better. One may be more flexible for solving my problem. So, I've included them both.
I want to build a list of reactors and their properties.
For each reactor I create an object that will eventually contain the properties of that reactor (like it's volume, operation start and end times,etc.)
I'd like to prevent the (duplicate) creation of a unit. In the example the creation of 'reactor3' with value 4 should be avoided.
What would be the best way to do that. Inside the class, using one of the methods or somehow else?
Your insights are greatly appreciated.