希望避免這樣的情況下屬性的創作:Python對象 - 避免與未知名
>>> class Point:
x = 0
y = 0
>>> a = Point()
>>> a.X = 4 #whoops, typo creates new attribute capital x
我創建了下面的物件,用來作爲超:
class StrictObject(object):
def __setattr__(self, item, value):
if item in dir(self):
object.__setattr__(self, item, value)
else:
raise AttributeError("Attribute " + item + " does not exist.")
雖然這看起來工作,蟒蛇documentation says of dir()
:
注:因爲
dir()
主要是爲了方便在交互式提示符下使用而提供,它試圖提供一組有趣的名稱,而不是試圖提供一組嚴格或一致定義的名稱,並且其詳細行爲可能會在不同版本間發生變化。例如,當參數是一個類時,元類屬性不在結果列表中。
有沒有更好的方法來檢查對象是否有屬性?
+1有關Pylint的有用信息。 – 2012-03-10 14:48:24