全部 我有一個python類實例化的問題。 因此,我有一堆存儲在同一目錄中的不同類型的數據,我只想使用僅適用於該類型的python類來處理它們的一種類型。不幸的是,數據的類型只有在通過該類讀入時才知道。 所以我想知道如果數據類型不正確,是否有辦法簡單地停止__init__()
中的類實例化,並且只是在讀取所有數據時傳遞給下一個數據集? 或者在類實例化時驗證它是個壞主意?對類實例化的驗證
非常感謝!
全部 我有一個python類實例化的問題。 因此,我有一堆存儲在同一目錄中的不同類型的數據,我只想使用僅適用於該類型的python類來處理它們的一種類型。不幸的是,數據的類型只有在通過該類讀入時才知道。 所以我想知道如果數據類型不正確,是否有辦法簡單地停止__init__()
中的類實例化,並且只是在讀取所有數據時傳遞給下一個數據集? 或者在類實例化時驗證它是個壞主意?對類實例化的驗證
非常感謝!
這樣做是爲了產生錯誤的正確方法如果提供給班級的數據是錯誤的類型:
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.
謝謝!這真的很有幫助! – Winston
你可以這樣做:
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
你能解釋,爲什麼「時,它是通過讀取的數據類型是唯一已知的這個班級「更具體地展示了你的數據。 – sberry
不好意思,所以數據是netcdf格式的,我只能知道它是一個圖像還是一個光譜,當我讀入並通過類查找它的'TYPE'屬性。 – Winston