Skip to content

Commit c752068

Browse files
committed
add slots
1 parent 6216e9a commit c752068

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

Class/slots.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,58 @@
11
# slots 魔法
22

3+
在 Python 中,我们在定义类的时候可以定义属性和方法。当我们创建了一个类的实例后,我们还可以给该实例绑定任意新的属性和方法。
4+
5+
看下面一个简单的例子:
6+
7+
```python
8+
class Point(object):
9+
def __init__(self, x=0, y=0):
10+
self.x = x
11+
self.y = y
12+
13+
>>> p = Point(3, 4)
14+
>>> p.z = 5 # 绑定了一个新的属性
15+
>>> p.z
16+
5
17+
>>> p.__dict__
18+
{'x': 3, 'y': 4, 'z': 5}
19+
```
20+
21+
在上面,我们创建了实例 p 之后,给它绑定了一个新的属性 z,这种动态绑定的功能虽然很有用,但它的代价是消耗了更多的内存。
22+
23+
因此,为了不浪费内存,可以使用 `__slots__` 来告诉 Python 只给一个固定集合的属性分配空间,对上面的代码做一点改进,如下:
24+
25+
```python
26+
class Point(object):
27+
__slots__ = ('x', 'y') # 只允许使用 x 和 y
28+
29+
def __init__(self, x=0, y=0):
30+
self.x = x
31+
self.y = y
32+
```
33+
34+
上面,我们给 `__slots__` 设置了一个元组,来限制类能添加的属性。现在,如果我们想绑定一个新的属性,比如 z,就会出错了,如下:
35+
36+
```python
37+
>>> p = Point(3, 4)
38+
>>> p.z = 5
39+
---------------------------------------------------------------------------
40+
AttributeError Traceback (most recent call last)
41+
<ipython-input-648-625ed954d865> in <module>()
42+
----> 1 p.z = 5
43+
44+
AttributeError: 'Point' object has no attribute 'z'
45+
```
46+
47+
使用 `__slots__` 有一点需要注意的是,`__slots__` 设置的属性仅对当前类有效,对继承的子类不起效,除非子类也定义了 `__slots__`,这样,子类允许定义的属性就是自身的 slots 加上父类的 slots。
48+
49+
# 小结
50+
51+
- __slots__ 魔法:限定允许绑定的属性.
52+
- `__slots__` 设置的属性仅对当前类有效,对继承的子类不起效,除非子类也定义了 slots,这样,子类允许定义的属性就是自身的 slots 加上父类的 slots。
53+
54+
# 参考资料
55+
56+
- [slots魔法 · Python进阶](https://eastlakeside.gitbooks.io/interpy-zh/content/slots_magic/)
57+
58+

0 commit comments

Comments
 (0)