定义类的__slots__属性节省内存的开销

import sys

class Student(object):

    def __init__(self, id, name, sex, age):
        self.id = id
        self.name = name
        self.sex = sex
        self.age = age


class Student_slots(object):

    __slots__ = ['id', 'name', 'sex', 'age'] #使用__slots__就没有__dict__的属性,就要重新声明实例的属性

    def __init__(self, id, name, sex, age):
        self.id = id
        self.name = name
        self.sex = sex
        self.age = age

s1 = Student(1, 'lin', 'male', 18)
s2 = Student_slots(1, 'lin', 'male', 18)

print set(dir(s1))-set(dir(s2)) #Student类比Student_slots多了__dict__, __weakref__'这个两个属性
print s1.__dict__  #以消耗内存为代价的动态绑定

print sys.getsizeof(s1.__dict__)

 

posted on 2017-04-12 19:47  miss_林  阅读(96)  评论(0编辑  收藏  举报

导航