property属性
定义
一个可以使实例方法用起来像实例属性一样的特殊关键字,可以对应于某个方法,通过使用property属性,能够简化调用者在获取数据的流程(使代码更加简明)。
property属性的定义和调用要注意以下几点:
调用时,无需括号,加上就错了;并且仅有一个self参数
实现property属性的两种方式
装饰器
新式类中的属性有三种访问方式,并分别对应了三个被
- @property对应读取
- @方法名.setter修改
- @方法名.deleter删除属性
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()方法有四个参数
- 第一个参数是方法名,调用 对象.属性 时自动触发执行方法
- 第二个参数是方法名,调用 对象.属性 = XXX 时自动触发执行方法
- 第三个参数是方法名,调用 del 对象.属性 时自动触发执行方法
- 第四个参数是字符串,调用 对象.属性.doc ,此参数是该属性的描述信息
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)
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。