[英]Best practice of class initialization in python
嗨,我想知道最佳實踐是在python中初始化類,同時確保我的屬性具有正確的數據類型。
我應該使用默認值初始化類屬性還是調用檢查功能?
class Foo:
# Call with default value
def __init__(self, bar=""):
self._bar = bar
# Calling set-function
def __init__(self, bar):
self._bar = ""
self.set_bar(bar)
def get_bar(self):
return self._bar
def set_bar(self, bar):
if not isinstance(bar, str):
raise TypeError("bar must be string")
self._bar = bar
def del_bar(self):
self._bar = ""
bar = property(get_bar, set_bar, del_bar, 'bar')
您可以嘗試以下代碼片段:
class Foo:
def __init__(self, bar=''):
self.bar = bar
@property
def bar(self):
return self._bar
@bar.setter
def bar(self, bar):
if isinstance(bar, str):
self._bar = bar
else:
raise TypeError('<bar> has to be of type string')
f = Foo('5') # works fine
g = Foo(5) # raises type error
即使在類實例化時未提供任何參數,也將執行檢查。 因此,即使您提供一個整數作為默認參數,它也會觸發異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.