我不認爲有一個更好的辦法不是要明確你的意圖,雖然也許你可以相信任何人創建Human
-object會明白,你不能500多年的歷史。
我相信最pythonic的方式是raise
一個有意義的異常,只要其中一個屬性不驗證。我還使用默認參數,使您不必從頭再來類型最常見的用例..
class Human:
def __init__(self, name, legs=2, hands=2, age=0, hair='blonde'):
if not isinstance(name, str):
raise TypeError("Name must be a string")
self.name = name
if legs > 2:
raise ValueError("More than 2 legs")
self.legs = legs
if hands > 2:
raise ValueError("More than 2 hands")
self.hands = hands
if age > 110:
raise ValueError("What, are you immortal?!")
self.age = age
if hair not in ['black', 'blonde', 'bold']:
raise ValueError("I'm sorry your hair color is not cool enough")
self.hair = hair
例子:
In [15]: Human(123)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-15-9998e6013647> in <module>()
----> 1 Human(123)
<ipython-input-13-65da6758e98d> in __init__(self, name, legs, hands, age, hair)
2 def __init__(self, name, legs=2, hands=2, age=0, hair='blonde'):
3 if not isinstance(name, str):
----> 4 raise TypeError("Name must be a string")
5 self.name = name
6
TypeError: Name must be a string
另外一個..
In [16]: Human("John", age=1500)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-16-09f5670add7c> in <module>()
----> 1 Human("John", age=1500)
<ipython-input-13-65da6758e98d> in __init__(self, name, legs, hands, age, hair)
17
18 if age > 110:
---> 19 raise ValueError("What, are you immortal?!")
20 self.age = age
21
ValueError: What, are you immortal?!
每個屬性的'if'語句.. – msvalkon
約一半時間,類型檢查/驗證是反模式。有一個原因是Python是動態輸入的。你確定你確實需要打字檢查嗎? –
fyi ... [最早記錄的年齡記錄是122](http://en.wikipedia.org/wiki/Oldest_people#Ten_verified_oldest_women_ever)。 –