property属性学习
定义spa
一个能够使实例方法用起来像实例属性同样的特殊关键字,能够对应于某个方法,经过使用property属性,可以简化调用者在获取数据的流程(使代码更加简明)。.net
property属性的定义和调用要注意如下几点:code
调用时,无需括号,加上就错了;而且仅有一个self参数htm
实现property属性的两种方式对象
装饰器
ci
新式类中的属性有三种访问方式,并分别对应了三个被文档
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
class
Goods:
def
__init__(
self
):
self
.age
=
18
@property
def
price(
self
):
# 读取
return
self
.age
# 方法名.setter
@price
.setter
# 设置,仅可接收除self外的一个参数
def
price(
self
, value):
self
.age
=
value
# 方法名.deleter
@price
.deleter
# 删除
def
price(
self
):
del
self
.age
# ############### 调用 ###############
obj
=
Goods()
# 实例化对象
obj.age
# 直接获取 age属性值
obj.age
=
123
# 修改age的值
del
obj.age
# 删除age属性的值
|
类属性
字符串
当使用类属性的方式建立property属性时,property()方法有四个参数get
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
class
Goods(
object
):
def
__init__(
self
):
self
.price
=
100
# 原价
self
.discount
=
0.8
# 折扣
def
get_price(
self
):
# 实际价格 = 原价 * 折扣
new_price
=
self
.price
*
self
.discount
return
new_price
def
set_price(
self
, value):
self
.price
=
value
def
del_price(
self
):
del
self
.price
# 获取 设置 删除 描述文档
PRICE
=
property
(get_price, set_price, del_price,
'价格属性描述...'
)
# 使用此方式设置
obj
=
Goods()
obj.PRICE
# 获取商品价格
obj.PRICE
=
200
# 修改商品原价
del
obj.PRICE
# 删除商品原价
|
使用property取代getter和setter方法
使用@property装饰器改进私有属性的get和set方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
class
Money(
object
):
def
__init__(
self
):
self
.__money
=
0
# 使用装饰器对money进行装饰,那么会自动添加一个叫money的属性,当调用获取money的值时,调用装饰的方法
@property
def
money(
self
):
return
self
.__money
# 使用装饰器对money进行装饰,当对money设置值时,调用装饰的方法
@money
.setter
def
money(
self
, value):
if
isinstance
(value,
int
):
self
.__money
=
value
else
:
print
(
"error:不是整型数字"
)
a
=
Money()
a.money
=
100
print
(a.money)
|
以上就是本文的所有内容,但愿对你们的学习有所帮助,也但愿你们多多支持脚本之家。