小编Mat*_*att的帖子

了解 Python 3.7 中类、namedtuple 和 __slots__ 的大小

在 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)

python documentation class python-3.7

5
推荐指数
1
解决办法
1746
查看次数

标签 统计

class ×1

documentation ×1

python ×1

python-3.7 ×1