我正在尝试将一些模块包装到类中,并开始使用属性。
将这两个答案合并在一起:making instance attribute read-only和validating attributes。
我希望能够创建DataFolder类的实例:
df = DataFolder(owner="me", path="/.data")
之后,我希望能够允许编辑owner
属性,但不能编辑path
属性。我希望能够在初始化时(path
和owner
)和之后(仅owner
)验证属性。
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
使用全局变量_path = None
并检查if self._path is not None:
中的@path.setter
是正确/最佳吗?代码工作正常,但我想知道是否存在是一种更好的方法。
答案 0 :(得分:0)
除了一件事外,它对我来说很好:_path = None
属于一个类。
这只是一个小小的改进:
class DataFolder(object):
def __init__(self, owner, path):
self._path = None # now it is an instance variable.
self.path = path
self.owner = owner
@property
def owner(self):
return self._owner
def _validate_owner(self, owner_value):
if "me" not in owner_value:
raise ValueError("invalid owner")
@owner.setter
def owner(self, owner_value):
self._validate_owner(owner_value)
self._owner = owner_value
@property
def path(self):
return self._path
def _validate_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 ValueError("invalid folder")
@path.setter
def path(self, path_value):
self._validate_path(path_value)
self._path = path_value
使用:
d = DataFolder('me', 'data')
print(d.path, d.owner)
d.path = 'new_data'
输出:
('data', 'me')
new_me
AttributeError: Cannot edit path of existing data folder