• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

jwang106


脚踏实地,日拱一卒。 建立新的神经链接,可不像公园散步那样简单。
  • 博客园
  • 联系
  • 管理

View Post

python slot

每个实例包含一个字典,slot 让实例变成tup 或list,减少内存,但不能再增加属性

For classes that primarily serve as simple data structures, you can often greatly reduce the memory footprint of instances by adding the slots attribute to the class defi‐ nition. For example:

class Date:
slots = ['year', 'month', 'day'] def init(self, year, month, day):

        self.year = year
        self.month = month
        self.day = day

When you define slots, Python uses a much more compact internal representation for instances. Instead of each instance consisting of a dictionary, instances are built around a small fixed-sized array, much like a tuple or list. Attribute names listed in the slots specifier are internally mapped to specific indices within this array. A side effect of using slots is that it is no longer possible to add new attributes to instances— you are restricted to only those attribute names listed in the slots specifier

posted on 2019-08-20 10:47  jwang106  阅读(317)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3