Pythonでは、先に定義したクラスC
に属性を追加できます。しかし、私はlist
に属性を追加することはできません - 結果のエラーメッセージがlist
がビルトインされているため、タイプであると説明していますPythonのどのオブジェクトに属性を動的に追加できますか?
>>> class C: pass
...
>>> C.foo = 1
>>> C.foo
1
>>> list.foo = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'list'
、C
のインスタンスに属性を追加することは可能であるが、 list
のインスタンスではありません。しかし、この場合には、エラーメッセージがはるかにあいまいです:
>>> o = C()
>>> o.bar = 2
>>> o.bar
2
>>> o = []
>>> o.bar = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'bar'
なぜlist
のインスタンスにメンバーを追加することはできませんか? list
はビルトインタイプなので、もう一度ですか?
は、動的に追加された属性を持つことができますか?
組み込み型でないものがあります。 –
強く関連しています。https://stackoverflow.com/questions/6738987/extension-method-for-python-built-in-types –