Imagine a factory that produces bottles and at the end, a label is attached to each bottle, indicating its contents.
So we have objects of class Bottle, and a function that attaches an object of type Label to each Bottle.
The issue then is that the label cannot be given to bottle in its __init__ function, as the label is created after the bottle. We could of course just add a flag that equals None, and mutate it later, but then we have two issues: a) mutation and b) we cannot differentiate between the situations where the label has not yet been put on and the situation where the label has been put on with a value equalling None.
What is the pythonic way to handle this?
My solution is below, which looks horrible! What else can I do?
class BottleWithLabel(Bottle):
def __init__(bottle, label)
self.bottle = bottle
self.label = label
def __getattribute__(attr):
if attr not in ['label']:
return getattr(self.bottle, attr)
return object.__getattribute__(self, attr)
# apply label
bottle = BottleWitLabel(bottle, label)
# get label
bottle.label
# check if bottle has undergone the labelling process
isinstance(bottle, BottleWithLabel)