天天看點

python計算空類型_python-為什麼SimpleNamespace的大小與空類的大...

考慮以下:

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)

我似乎在這裡追逐自己的尾巴.

我在64位系統上使用CPython 3.5.對于一些我無法查明的錯誤引用,這8個位元組似乎正好合适.