I am trying to wrap some of my modules into classes and have started playing with properties.
Working on combining these two answers together: making instance attribute read-only and validating attributes.
I want to be able to create an instance of DataFolder class:
df = DataFolder(owner="me", path="/.data")
After that I want to be able to allow editing the owner
attribute, but not the path
attribute. I want to be able to validate the attributes at the moment of initialization (both path
and owner
) and afterwards (yet owner
only).
class DataFolder(object):
_path = None
#----------------------------------------------------------------------
def __init__(self,owner,path):
self.path = path
self.owner = owner
@property
#----------------------------------------------------------------------
def owner(self):
return self._owner
@owner.setter
#----------------------------------------------------------------------
def owner(self,owner_value):
if "me" not in owner_value:
raise Exception("invalid owner")
self._owner = owner_value
@property
#----------------------------------------------------------------------
def path(self):
return self._path
@path.setter
#----------------------------------------------------------------------
def path(self,path_value):
if self._path is not None:
raise AttributeError("Cannot edit path of existing data folder")
if "dat" not in path_value:
raise Exception("invalid folder")
self._path = path_value
Is it correct/best to use the global variable _path = None
and check if self._path is not None:
in @path.setter
? The code works fine, but I am wondering if there is a better approach.