2017-04-07 47 views
0

初始化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.') 
+1

擺脫了檢查。編寫適當的文檔/文檔。從這裏是垃圾 - >垃圾。 – timgeb

回答

-1

如果您需要對每個賦值運行驗證,則屬性是您的方式。

請記住,當您有很多任務(如循環中)時,這可能會有性能問題。

你的問題可以通過驗證輸入只能在類的啓動來解決,你最好有你的類cleanvalidate方法,然後調用它在__init__ FUNC結束。

使用此方法,您可以隨時調用您的clean方法,並省略性能比驗證更重要的調用(這是django forms的工作方式)。

在你的情況,你正在試圖做的過載/調度,看看在docs

+0

爲什麼選擇downvoted?請解釋 –

+0

我不知道誰確實做了downvote。 – Mihai

+0

謝謝你的答案,但你能詳細一點嗎?我需要對不同的參數使用不同的驗證函數,我在考慮是否可以在'__init __()'中刪除if並同時保留'_ *'。 – Mihai