【发布时间】:2017-04-07 11:56:27
【问题描述】:
在初始化 python 类时,初始化属性和检查提供的参数的最佳方法是什么?假设__init__() 中有多个参数,其中一些必须遵守一定的规则。还需要为其中一些设置 setter 和 getter。我可以从下面想到选项。你觉得它怎么样?有没有更好的选择?
选项:初始化属性None 并调用执行检查的setter。
class A(object):
def __init__(self, p1=None, ..., pn=None):
self._p1 = None
...
self._pn = None
if p1 is not None:
self.p1 = p1
...
if pn is not None:
self.pn = pn
@p1.setter
def p1(self, p1):
# If p1 is int we can just take it
if isinstance(p1, int):
self._p1 = p1
# If p1 is str we have to obtain it differently
elif isinstance(p1, str):
self._p1 = self._gen_some_p_from_str(p1)
else:
raise Exception('Incorrect p1 type provided.')
...
@pn.setter
def pn(self, pn):
# If pn instance of SomeOtherClass it should be also great
if isinstance(pn, SomeOtherClass):
if pn.great():
self._pn = pn
else:
raise exception('pn not great')
# pn can be also str, and then we should get it
elif isinstance(pn, str):
self._pn = self._get_some_other_p_from_str(pn)
else:
raise Exception('Incorrect pn type provided.')
【问题讨论】:
-
摆脱支票。编写适当的文档/文档字符串。从这里是垃圾进 -> 垃圾出。