1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
|
"""
装饰器property:
使一个方法看起来就像类属性一样
"""
#例子1
class
A:
def
__init__(
self
, x, y):
self
.__x
=
x
#私有变量
self
.__y
=
y
def
__add(
self
):
#私有方法
return
self
.__x
+
self
.__y
@
property
def
sum
(
self
):
#通过property装饰器修饰后将方法看起来就像属性一样
return
self
.__add()
if
__name__
=
=
'__main__'
:
a
=
A(
5
,
6
)
print
(a.
sum
)
#外部调用sum,看起来就如同属性,这个属性实际上是一个不被计算功能的方法
#例子2
class
Foo:
@
property
def
foo(
self
):
return
"bar"
f
=
Foo()
print
(f.foo)
例子
3
class
Foo:
@
property
def
foo(
self
):
return
self
._foo
@foo.setter
#使用foo方法的setter属性又装饰了这个foo方法,这个foo和上面的foo只是名字相同,实际是不同的
def
foo(
self
, value):
self
._foo
=
value
f
=
Foo()
f.foo
=
100
print
(f.foo)
#一定要注意了,由property装饰器装饰后的函数返回的是一个对象
#例子4
class
Silly:
@
property
def
silly(
self
):
print
(
"You are getting silly"
)
return
self
._silly
#返回的是一个property对象
@silly.setter
def
silly(
self
, value):
print
(
"You are making silly {}"
.
format
(value))
self
._silly
=
value
@silly.deleter
#删除函数(目前我也不知道这么去使用它)
def
silly(
self
):
print
(
"Whoah you killed silly!"
)
del
self
._silly
s
=
Silly
s.silly
=
100
print
(s.silly)
#再看最后的一个例子,一个苹果类中的价格属性
class
Apple:
def
__init__(
self
, price):
self
.price
=
price
a
=
Apple(
19
)
print
(a.price)
a.price
=
20
#随意被更改了,存在数据安全问题
print
(a.price)
#改进代码v1.0
class
Apple:
def
__init__(
self
, price):
self
._price
=
price
#将属性增加单下划线,变成半保护
a
=
Apple(
19
)
#初始化价格
print
(a._price)
#打印
a.price
=
25
#尝试的修改
print
(a._price)
#貌似没有修改成功,还是原来的19
#继续改进 v1.0.1
class
Apple:
def
__init__(
self
, price):
self
._price
=
price
a
=
Apple(
"hello"
)
#price是价格,但被人传入的是字符串,也就是说被随意传入不同的数据类型的数据,需要继续改进
print
(a._price)
#继续改进 v1.0.2
class
Apple(
object
):
def
get_price(
self
):
return
self
.__price
def
set_score(
self
, price):
if
not
isinstance
(price,
int
):
raise
ValueError(
'Price must be an integer!'
)
self
.__price
=
price
a
=
Apple()
a.set_score(
19
)
#那么可以再试试传入字符串,那么则会引发异常
print
(a.get_price())
#最终版本 v2.0
class
Apple(
object
):
@
property
def
get_price(
self
):
try
:
return
self
.__price
except
AttributeError:
print
(
"No Data..."
)
@get_price.setter
#@property本身又创建了另一个装饰器@get_price.setter,负责把一个setter方法变成属性赋值
def
set_score(
self
, price):
if
not
isinstance
(price,
int
):
raise
ValueError(
'Price must be an integer!'
)
self
.__price
=
price
a
=
Apple()
a.set_score
=
20
print
(a.get_price)
|
本文转自 TtrToby 51CTO博客,原文链接:http://blog.51cto.com/freshair/2064249