2012-10-31 26 views
0

全部 我有一個python類實例化的問題。 因此,我有一堆存儲在同一目錄中的不同類型的數據,我只想使用僅適用於該類型的python類來處理它們的一種類型。不幸的是,數據的類型只有在通過該類讀入時才知道。 所以我想知道如果數據類型不正確,是否有辦法簡單地停止__init__()中的類實例化,並且只是在讀取所有數據時傳遞給下一個數據集? 或者在類實例化時驗證它是個壞主意?對類實例化​​的驗證

非常感謝!

+0

你能解釋,爲什麼「時,它是通過讀取的數據類型是唯一已知的這個班級「更具體地展示了你的數據。 – sberry

+0

不好意思,所以數據是netcdf格式的,我只能知道它是一個圖像還是一個光譜,當我讀入並通過類查找它的'TYPE'屬性。 – Winston

回答

0

這樣做是爲了產生錯誤的正確方法如果提供給班級的數據是錯誤的類型:

class MyClass(object): 
    def __init__(self, data): 
     if not isinstance(data, correct_type): 
      raise TypeError("data argument must be of type X") 

,然後用試試換你實例除了條款:

try: 
    myInstance = MyClass(questionable_data) 

except TypeError: 
    #data is not the correct type. "pass" or handle in an alternative way. 

這是有利的,因爲它使得該數據需要某種類型的明確明顯的事實。

另一種選擇是做的sberry說,和之前顯式測試數據類型試圖實例化一個類:

if isinstance(data, correct_type): 
    myInstance = MyClass(data) 
else: 
    #data is not the correct type. "pass" or handle in an alternative way. 
+0

謝謝!這真的很有幫助! – Winston

0

你可以這樣做:

class MyClass(object): 
    def __init__(self,data): 
     if type(data) is int: #In this example we don't want an int, we want anything else 
      pass 
     else: 
      #do stuff here 

然後使用它像:

MyClass('This is ok') 

MyClass(92) #This is not ok 
+1

這是如何停止實例化?另外,爲什麼不'if isinstance(data,int):foo = MyClass(data)' – sberry

+0

這對我來說已經夠用了,儘管它仍然實例化了它。但我想這不會佔用太多的記憶。謝謝! – Winston