File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11# 使用 @property
22
3+ 在使用 ` @property ` 之前,让我们先来看一个简单的例子:
4+
5+ ``` python
6+ class Exam (object ):
7+ def __init__ (self , score ):
8+ self ._score = score
9+
10+ def get_score (self ):
11+ return self ._score
12+
13+ def set_score (self , val ):
14+ if val < 0 :
15+ self ._score = 0
16+ elif val > 100 :
17+ self ._score = 100
18+ else :
19+ self ._score = val
20+
21+ >> > e = Exam(60 )
22+ >> > e.get_score()
23+ 60
24+ >> > e.set_score(70 )
25+ >> > e.get_score()
26+ 70
27+ ```
28+
29+ 在上面,我们定义了一个 Exam 类,为了避免直接对 ` _score ` 属性操作,我们提供了 get_score 和 set_score 方法,这样起到了封装的作用,把一些不想对外公开的属性隐蔽起来,而只是提供方法给用户操作,在方法里面,我们可以检查参数的合理性等。
30+
31+ 这样做没什么问题,但是我们有更简单的方式来做这件事,Python 提供了 ` property ` 装饰器,被装饰的方法,我们可以将其『当作』属性来用,看下面的例子:
32+
33+ ``` python
34+ class Exam (object ):
35+ def __init__ (self , score ):
36+ self ._score = score
37+
38+ @ property
39+ def score (self ):
40+ return self ._score
41+
42+ @score.setter
43+ def score (self , val ):
44+ if val < 0 :
45+ self ._score = 0
46+ elif val > 100 :
47+ self ._score = 100
48+ else :
49+ self ._score = val
50+
51+ >> > e = Exam(60 )
52+ >> > e.score
53+ 60
54+ >> > e.score = 90
55+ >> > e.score
56+ 90
57+ >> > e.score = 200
58+ >> > e.score
59+ 200
60+ ```
61+
62+ 在上面,我们给方法 score 加上了 ` @property ` ,于是我们可以把 score 当成一个属性来用,此时,又会创建一个新的装饰器 ` score.setter ` ,它可以把被装饰的方法变成属性来赋值。
63+
64+ 另外,我们也不一定要使用 ` score.setter ` 这个装饰器,这时 score 就变成一个只读属性了:
65+
66+ ``` python
67+ class Exam (object ):
68+ def __init__ (self , score ):
69+ self ._score = score
70+
71+ @ property
72+ def score (self ):
73+ return self ._score
74+
75+ >> > e = Exam(60 )
76+ >> > e.score
77+ 60
78+ >> > e.score = 200 # score 是只读属性,不能设置值
79+ -------------------------------------------------------------------------- -
80+ AttributeError Traceback (most recent call last)
81+ < ipython- input - 676 - b0515304f6e0> in < module> ()
82+ ---- > 1 e.score = 200
83+
84+ AttributeError : can' t set attribute
85+
86+ ```
87+
88+ # 小结
89+
90+ - ` @property ` 把方法『变成』了属性。
91+
92+
You can’t perform that action at this time.
0 commit comments