创建大量实例节省内存 slots
# 使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的
import sys
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):
# 为节省内存,阻止动态绑定属性,减少实例中的__dict__,从而达到减少内存开销的目的
__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(dir(p1))
print(dir(p2))
print('*'*80)
print(set(dir(p1)) - set(dir(p2))) # {'__dict__', '__weakref__'}
# 动态绑定属性
print(p1.__dict__) # 动态绑定属性 {'level': 1, 'status': 0, 'uid': '0001', 'name': 'Jim'}
# 添加属性
p1.x = 123
print(p1.__dict__) # {'name': 'Jim', 'uid': '0001', 'x': 123, 'level': 1, 'status': 0}
p1.__dict__['y'] = 99
print(p1.y) # 99
# 删除属性
delattr(p1, 'x') # 删除p1的x属性
print(p1.__dict__) # {'level': 1, 'y': 99, 'uid': '0001', 'status': 0, 'name': 'Jim'}
print('*'*80)
print(sys.getsizeof(p1.__dict__)) # 164