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

后端 未结 7 1297
囚心锁ツ
囚心锁ツ 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:41

    It is simply due to optimization.

    Dicts are relatively large.

    >>> import sys
    >>> sys.getsizeof((lambda:1).__dict__)
    140
    

    Most (maybe all) classes that are defined in C do not have a dict for optimization.

    If you look at the source code you will see that there are many checks to see if the object has a dict or not.

提交回复
热议问题