__slots__
By default, instances of both old and new-style classes have a dictionary for attribute storage. This wastes space for objects having very few instance variables. The space consumption can become acute when creating large numbers of instances.
默认 ,旧的和新式类 有一个存储属性的字典。这会浪费一个拥有很少实例变量对象的空间。当创建大量实例的时候,空间消耗变的很严重。
__slots__
This class variable can be assigned a string, iterable, or sequence of strings with variable names used by instances. If defined in a new-style class, __slots__ reserves space for the declared variables and prevents the automatic creation of__dict__ and __weakref__ for each instance.
这个类的变量可以指定为字符串 可迭代的对象 字符串序列与变量使用的名称的实例。如果定义在一个新型的类,__slots__ 会存储声明变量的空间并阻止自动创建那些不必要的变量,其实就是保护那些一开始创建变量的空间,再想创建,不让你创建了。
class A(object):
__slots__ = "x" abc = A() abc.x = "xxx" print abc.xXXX
class A(object):
__slots__ = "x" abc = A() abc.y = "yyy" print abc.yNote: AttributeError: 'A' object has no attribute 'y'
属性被固定是X,再想往里面加,不让了。所以报错。
下面是个特列:
class A(object):
pass class B(A): __slots__='b' b = "bbb" c = B() print c.b以上正常打印 bbb
class A(object): pass class B(A): __slots__='b' b = "bbb" c = B() c.e = "eee" print c.e
e没有定义在__slots__中,也能打印了,这里是B继承了A