5月 242013
>>> 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 "", line 1, in AttributeError: 'My2' object has no attribute 'hoge'
slotsを使えば、用意された属性のみ定義可能にできる。