Skip to content

Commit a435e63

Browse files
committed
add slots sample
1 parent 0ce9ce4 commit a435e63

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

py3/oop_advance/use_slots.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
class Student(object):
5+
__slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
6+
7+
class GraduateStudent(Student):
8+
pass
9+
10+
s = Student() # 创建新的实例
11+
s.name = 'Michael' # 绑定属性'name'
12+
s.age = 25 # 绑定属性'age'
13+
# ERROR: AttributeError: 'Student' object has no attribute 'score'
14+
try:
15+
s.score = 99
16+
except AttributeError as e:
17+
print('AttributeError:', e)
18+
19+
g = GraduateStudent()
20+
g.score = 99
21+
print('g.score =', g.score)

0 commit comments

Comments
 (0)