__slots__でオブジェクトに属性を追加できないようにする

>>> class My(object):
...   pass
...
>>> my = My()
>>> my.hoge = "Hello"     #属性は自由に追加できる
>>> print my.hoge
Hello
>>> class My2(object):
...   __slots__ = ["fuga"]  #fugaという属性のみ許可する
...   pass
...
>>> my2 = My2()
>>> my2.fuga = "hello"
>>> print my2.fuga
hello
>>> my2.hoge = "world"   #属性追加できない
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'My2' object has no attribute 'hoge'

slotsを使えば、用意された属性のみ定義可能にできる。

関連記事:

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)