__slots__作用
1.减少内存消耗
2.限制添加类属性及类初始化参数
实现__slots__
1.限制单个类属性
class Base(object): __slots__ = ['name'] pass
B = Base() B.name = 'John'
2.限制多个类属性,在__slots__的列表中继续添加即可
class Base(object): __slots__ = ['name','age'] pass
B = Base() B.name = 'John' B.age = 18
当添加类属性为非__slots__列表中的参数,会报错 AttributeError: 'Base' object has no attribute 'name1'
class Base(object): __slots__ = ['name'] pass B = Base() B.name1 = 'John' #AttributeError: 'Base' object has no attribute 'name1'
同样,__slots__会限制类初始化参数
class Base(object): __slots__ = ['name'] def __init__(self,name,age): self.name = name self.age = age pass B = Base('John',18) #AttributeError: 'Base' object has no attribute 'age'
节约内存
由于默认情况下每个类都会有一个dict,通过__dict__访问,这个dict维护了这个实例的所有属性。如果类中使用__slots__时,该对象不会自动产生__dict__属性
class Base(object): __slots__ = ['name'] def __init__(self,name): self.name = name pass B = Base('John') print(B.__dict__) #打印报错AttributeError: 'Base' object has no attribute '__dict__' class Base(object): # __slots__ = ['name'] def __init__(self,name): self.name = name pass B = Base('John') print(B.__dict__) # {'name': 'John'}