Python如何创建大量实例节省内存

Jackey Python 1,801 次浏览 没有评论
# 如何创建大量实例节省内存
class Player(object):
    def __init__(self, uid, name, status=0, level=1):
        self.uid = uid
        self.name = name
        self.status = status
        self.level = level


class Player2(object):
    # 定义类的__slots__ 属性,它是用来声明实例属性名字的列表
    __slots__ = ['uid', 'name', 'status', 'level']

    def __init__(self, uid, name, status=0, level=1):
        self.uid = uid
        self.name = name
        self.status = status
        self.level = level


p1 = Player('0001', 'Jim')
p2 = Player2('0001', 'Jim')

print(set(dir(p1)) - set(dir(p2)))

import sys

print(sys.getsizeof(p1.__dict__))

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go