class Student(object):
__slots__ = ['name', 'age']
def __init__(self, name, age):
self.name = name
self.age = age
self.grade = 0
if __name__ == '__main__':
try:
s = Student('Li', 20)
except Exception as e:
print(e)
# 'Student' object has no attribute 'grade'
import psutil
import os
class Student1(object):
def __init__(self, name, age, id):
self.name = name
self.age = age
self.id = id
if __name__ == '__main__':
process = psutil.Process(os.getpid())
mem_1 = process.memory_info().rss
print('mem1:', mem_1)
s = [Student1('python', 20, x) for x in range(1000 * 1000)]
mem_2 = process.memory_info().rss
print('mem2:', mem_2)
print('noslot_mem:', mem_2 - mem_1)
import psutil
import os
class Student2(object):
__slots__ = ['name', 'age', 'id']
def __init__(self, name, age, id):
self.name = name
self.age = age
self.id = id
if __name__ == '__main__':
process = psutil.Process(os.getpid())
mem_1 = process.memory_info().rss
print('mem1:', mem_1)
s = [Student2('python', 20, x) for x in range(1000 * 1000)]
mem_2 = process.memory_info().rss
print('mem2:', mem_2)
print('slot_mem:', mem_2 - mem_1)
本系列文章和代码已经作为项目归档到github,仓库地址:jumper2014/PyCodeComplete。大家觉得有帮助就请在github上star一下,你的支持是我更新的动力。什么?你没有github账号?学习Python怎么可以没有github账号呢,快去注册一个啦!