Can't set attributes on instance of “object” class

后端 未结 7 1216
囚心锁ツ
囚心锁ツ 2020-11-22 10:10

So, I was playing around with Python while answering this question, and I discovered that this is not valid:

o = object()
o.attr = \'hello\'
<
相关标签:
7条回答
  • 2020-11-22 10:42

    As other answerers have said, an object does not have a __dict__. object is the base class of all types, including int or str. Thus whatever is provided by object will be a burden to them as well. Even something as simple as an optional __dict__ would need an extra pointer for each value; this would waste additional 4-8 bytes of memory for each object in the system, for a very limited utility.


    Instead of doing an instance of a dummy class, in Python 3.3+, you can (and should) use types.SimpleNamespace for this.

    0 讨论(0)
提交回复
热议问题