なぜPythonでオブジェクトに属性を追加できないのですか? (Pythonのシェルで書かれた)
>>> o = object()
>>> o.test = 1
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
o.test = 1
AttributeError: 'object' object has no attribute 'test'
>>> class test1:
pass
>>> t = test1()
>>> t.test
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
t.test
AttributeError: test1 instance has no attribute 'test'
>>> t.test = 1
>>> t.test
1
>>> class test2(object):
pass
>>> t = test2()
>>> t.test = 1
>>> t.test
1
>>>
なぜあなたはそれに属性を追加することを可能に反対しないのですか?
インスタンスメンバーの割り当てを防止するために、* object *クラスが\ _ \ _ slots \ _ \ _を使用していると言っています。これは前提か事実ですか(つまり、* object *の実装にありますか)? *オブジェクト*インスタンスからの\ _ \ dict \ _ \ _の単なる不在は、指標ではないからです。 OPの* test1 *クラスのインスタンスは、dir()で呼び出されたときに\ _ \ _ dict \ _ \ _と同じ欠落を示しますが、インスタンスメンバーの割り当ては可能です。 – ThomasH
@ThomasH、私が答えに加えたノートを見てください。 – ars