【发布时间】:2020-08-18 22:35:26
【问题描述】:
我在几个案例中发现 - 对于某些类属性 - 我的 __init__ 定义与我的 @attribute.setter 完全相似到令人讨厌的程度,激励示例:
class Eg:
__init__(self, att):
if #correct type and form
#do some more checks/formatting
self._att = att
@property
def att(self):
return self._att
@att.setter
def att(self, att):
if #correct type and form
#do some more checks/formatting
self._att = att
我的问题是,如果简单地调用对象初始化的 setter 是否有问题?一个例子:
class Eg:
__init__(self, att):
self.att = att
@property
def att(self):
return self._att
@att.setter
def att(self, att):
if #correct type and form
#do some more checks/formatting
self._att = att
非常感谢
【问题讨论】:
-
我会说这是好的做法。您可能希望在
__init__中应用与其他地方相同的验证,并且在__init__和 setter 中重复验证代码是没有意义的。
标签: python class properties