在 Pycon2016 上观看 Nina Zahkarenko 的 Python 内存管理演讲(链接)后,似乎 dunder 方法__slots__是一种减少对象大小和加速属性查找的工具。
我的期望是普通类将是最大的,而__slots__/namedtuple方法会节省空间。然而,一个快速的实验sys.getsizeof()似乎表明并非如此:
from collections import namedtuple
from sys import getsizeof
class Rectangle:
'''A class based Rectangle, with a full __dict__'''
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
class SlotsRectangle:
'''A class based Rectangle with __slots__ defined for attributes'''
__slots__ = ('x', 'y', 'width', 'height')
def __init__(self, x, y, width, height): …Run Code Online (Sandbox Code Playgroud)