# python __slots__

python新模式的class，即从object继承下来的类有一个变量是__slots__，slots的作用是阻止在实例化类时为实例分配dict，默认情况下每个类都会有一个dict,通过__dict__访问，这个dict维护了这个实例的所有属性，举例如下
class base(object):
v = 1
def __init__(self):
pass

b = base()
print b.__dict__
b.x = 2
print b.__dict__

{}
{'x':2}

class base(object):
__slots__ = ('y')
v = 1
def __init__(self):
pass

b = base()
print b.__dict__
b.x = 2              //error,不能增加新的变量
print b.__dict__

class base(object):
__slots=('y',)
y = 2
v = 1
def __init__(self):
pass

b = base()
print b.__dict__
b.x = 2
print b.__dict__

Notes on using __slots__

• Without a __dict__ variable, instances cannot be assigned new variables not listed in the __slots__ definition. Attempts to assign to an unlisted variable name raise an AttributeError. If dynamic assignment of new variables is desired, then add '__dict__' to the sequence of strings in the __slots__ declaration. (Changed in Python version 2.3)
• Without a __weakref__ variable for each instance, classes defining __slots__ do not support weak references to its instances. If weak reference support is needed, then add '__weakref__' to the sequence of strings in the __slots__ declaration. (Changed in Python version 2.3)
• __slots__ are implemented at the class level by creating descriptors ( 3.4.2.2) for each variable name. As a result, class attributes cannot be used to set default values for instance variables defined by __slots__; otherwise, the class attribute would overwrite the descriptor assignment.
• If a class defines a slot also defined in a base class, the instance variable defined by the base class slot is inaccessible (except by retrieving its descriptor directly from the base class). This renders the meaning of the program undefined. In the future, a check may be added to prevent this.
• The action of a __slots__ declaration is limited to the class where it is defined. As a result, subclasses will have a __dict__ unless they also define __slots__.
• __slots__ do not work for classes derived from "variable-length" built-in types such as long, str and tuple.
• Any non-string iterable may be assigned to __slots__. Mappings may also be used; however, in the future, special meaning may be assigned to the values corresponding to each key.

#### python __slot__的用法

2017-10-16 12:47:51

#### python __slots__ 详解（上篇）

2016-10-23 10:55:25

#### Python __slots__ 作用

2016-10-13 08:43:26

#### python中的__slot__

2014-12-09 15:12:19

#### __slots__为什么能节省内存？

2017-01-10 23:06:27

#### python __slots__ 使用

2013-10-12 14:17:46

#### Python的__slots__

2016-04-26 11:03:10

#### pyqt python thread signal slot 转载一篇感觉不错的代码，算做个笔记吧

2015-03-25 11:06:09

#### python类：面向对象、继承、slot、多重继承

2015-06-05 20:38:07

#### PyQt之玩转signal(信号)与slot(槽)一：介绍及简单实例

2015-07-22 17:14:50