I've a class like following:
class Invoice
def __init__(self, invoice_id):
self.invoice_id = invoice_id
self._amount = None
@property
def amount(self):
return self._amount
@amount.setter
def amount(self, amount):
self._amount = amount
In the above example, whenever I would try to get invoice amount without setting its value, I would get a None, like following:
invoice = Invoice(invoice_id='asdf234')
invoice.amount
>> None
But in this situation, None is not the correct default value for amount. I should be able to differentiate between amount value as None vs amount value not been set at all. So question is following:
- How do we handle cases when class property doesn't have a right default value ? In the above example if I remove
self._amount = Nonefrom init, I would get AttributeError for self._amount and self.amount would return a valid value only after I callinvoice.amount = 5. Is this the right way to handle it ? But this also leads to inconsistency in object state as application would be changing instance properties at runtime. - I've kept amount as a property for invoice for better understanding and readability of Invoice and its attributes. Should class properties only be used when we're aware of its init / default values ?
@propertyat all if it acts exactly like a field? Anyway, some relevant questions to decide what kind of approach you want are: 1) what does an invoice with anamountofNonemean? 2) is an invoice whoseamounthas never been set supposed to exist, or does its existence always indicate a programming error?Invoiceobject until you have both the ID and its amount.