I want to define a class that ensures some constraints when a property is set/modified. Furthermore, I want to be able to set the property value on construction, with the same constraints. Simplified example:
class MyClass(object):
def __init__(self, attrval):
self.myattr = attrval
@property
def myattr(self):
return self._myattr
@myattr.setter
def myattr(self, value):
if value is None:
raise ValueError("Attribute value of None is not allowed!")
self._myattr = value
I'm calling the property setter right from init(), so the property is the only place where self._myattr is accessed directly. Are there any problems or caveats in using a property like this (like a missing or invalid creation of _myattr)? Maybe when (multiple) inheritance comes in? Is there a PEP or some other "official" statement about how to properly initialize properties from init()?
Most property examples I found do not use the property setter from the constructor. In How to set a python property in __init__, the underlying attribute gets created explicitly before setting the property. Some people think that each single attribute must be explicitly initialized in init(), that's why my code example feels a bit odd.