初始化python類時初始化屬性和檢查提供的參數的最佳方法是什麼?假設__init__()
中有多個參數,其中一些參數必須符合某些規則。對於其中的一些人來說,也需要有制定者和獲得者。我可以從下面考慮這個選項。它如何看待你?有沒有更好的選擇?最佳實踐python init檢查
選項:初始化屬性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.')
擺脫了檢查。編寫適當的文檔/文檔。從這裏是垃圾 - >垃圾。 – timgeb