I have a question regarding variable linking between objects. Because I'm learning Python programming by myself, I may have bad habits…
I am programming a module which will save me a lot of labor by managing by itself the standard configparser module. I just have to pass to it as an argument, the list of the application's variables, and just tell it "load()" and "save()" to let it do all the job automatically (create new config file, load values into variables, check updates, etc…). It works perfectly with "true objects" like tkinter variables, but with variables containing simple numeric or string value, the value only is copied, not the object's "address".
Here's an example, it is an extremely simplified script focusing the problematic part but keeps the architecture of my module:
class Sauce:
"""Consider this class a Python standard module, so don't modify it."""
def __init__(self, ingredient):
self.ingredient = ingredient
def set(self, result):
self.ingredient = result
def get(self):
return self.ingredient
class Heater:
def __init__(self, ingredients_list):
self.ingredients_list = ingredients_list
def heat(self):
for item in self.ingredients_list:
if item['type'] == 'sauce':
item['ingredient'].set('caramel')
elif item['type'] == 'cereal':
item['ingredient'] = 'popcorn'
class Cooking:
def __init__(self):
self.cereal = 'corn'
self.sauce = Sauce('sugarAndWater')
print('We will cook these ingredients: {0} and {1}'.format(self.cereal, self.sauce.get()))
print('After cooking we should theorically get "popcorn" and "caramel"')
self.heater = Heater([{'type':'cereal', 'ingredient':self.cereal}, {'type':'sauce', 'ingredient':self.sauce}])
self.heater.heat()
print('But in reality we\'ve got:', self.cereal, self.sauce.get())
if __name__ == '__main__':
start = Cooking()
There are now the questions:
- Is it ok to directly transfer objects as an argument (self.sauce) to be modified by the instanced object (self.heater)?
- If 1 is yes, is there any trick to make a common variable (self.cereal) to work as expected?