【发布时间】:2017-02-06 23:06:32
【问题描述】:
考虑以下几点:
In [1]: import types
In [2]: class A:
...: pass
...:
In [3]: a1 = A()
In [4]: a1.a, a1.b, a1.c = 1, 2, 3
In [5]: a2 = types.SimpleNamespace(a=1,b=2,c=3)
In [6]: sys.getsizeof(a1)
Out[6]: 56
In [7]: sys.getsizeof(a2)
Out[7]: 48
这种尺寸差异来自哪里?正在看:
In [10]: types.__file__
Out[10]: '/Users/juan/anaconda3/lib/python3.5/types.py'
我发现:
import sys
# Iterators in Python aren't a matter of type but of protocol. A large
# and changing number of builtin types implement *some* flavor of
# iterator. Don't check the type! Use hasattr to check for both
# "__iter__" and "__next__" attributes instead.
def _f(): pass
FunctionType = type(_f)
LambdaType = type(lambda: None) # Same as FunctionType
CodeType = type(_f.__code__)
MappingProxyType = type(type.__dict__)
SimpleNamespace = type(sys.implementation)
好吧,这没什么:
>>> import sys
>>> sys.implementation
namespace(cache_tag='cpython-35', hexversion=50660080, name='cpython', version=sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0))
>>> type(sys.implementation)
<class 'types.SimpleNamespace'>
我好像在这里追自己的尾巴。
我能够找到 this related question,但我的特定查询没有答案。
我在 64 位系统上使用 CPython 3.5。这 8 个字节的大小似乎正好适合一些我无法确定的错误引用。
【问题讨论】:
-
它的出现是因为它们是不同的类型......而
sys.getsizeof并没有告诉你一个对象消耗的总内存,那么为什么这两种类型应该是相同的呢?例如,在您的示例中,getsizeof(A())(“空”A)也是 56。 -
对,添加属性是一个红鲱鱼。但是即使我只有一个空类
class A: pass; a = A()和s = SimpleNamespace(),仍然存在差异。 -
当然......但是,为什么您希望两个空类型具有相同的大小?您是否希望
set()和[]具有相同的大小? -
@donkopotamus 不一定,但我想了解为什么。
-
SimpleNamespace类的定义在namespaceobject.c源文件中。
标签: python