dictのインスタンスにattributeがセットできない(2)
dictと言うより組み込み型全てでできないみたい。
>>> list().y = 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'list' object has no attribute 'y'
__slots__属性を与えてやれば同様な制限をかけられる。しかし、__slots__属性が見当たらない。
>>> class Foo(object): __slots__ = ['y'] ... >>> Foo().y = 1 # ok! >>> Foo().z = 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Foo' object has no attribute 'z' >>> '__slots__' in dir(dict()) False
また、dictのインスタンスに__dict__属性も見つからないが、自分で定義したクラスには新旧どちらのクラスにも定義されるし、好き勝手に属性も追加できる。
>>> dict().__dict__ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'dict' object has no attribute '__dict__' >>> class Old: pass ... >>> class New(object): pass ... >>> Old().__dict__ {} >>> New().__dict__ {} >>> Old().y = 1 >>> New().y = 1
あと、旧クラスは、__dict__がdir()で見えないのに何故存在するのか。
>>> '__dict__' in dir(Old) False >>> '__dict__' in dir(Old()) False >>> Old.__bases__ ()
分からないことが多すぎ。結局、まとめると以下の2つのことが分からない。
- 組み込み型のインスタンスはどういう仕組みで新たな属性がセットできないのか
- dir()で見えない属性が何故使えるのか
分かる人いたら教えて欲しい…。