property使用简介
功能简介
1) 把类方法变成只读属性
2) setter和getter的另一种实现
代码演示1
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ ='shouke'
classUser(object):
def__init__(self, username, password):
self._username = username
self._password = password
@property
defusername(self):
returnself._username
@username.setter
defusername(self, username):
self._username = username
@property
defpassword(self):
returnself._password
@password.setter
defpassword(self, password):
self._password = password
if__name__ =='__main__':
boy = User('shouke','shouke2014')
print('对象用户名:', boy.username)
boy.username ='shou ke'
print('修改后的用户名:', boy.username)
print('通过修改属性值来修改密码')
boy._password =2014
print('修改后的用户密码:', boy._password)
boy.password ='shouke2016'
print('通过方法属性来修改密码,修改后的用户密码:', boy._password)
运行结果:
对象用户名: shouke
修改后的用户名: shou ke
通过修改属性值来修改密码
修改后的用户密码: 2014
通过方法属性来修改密码,修改后的用户密码: shouke2016
注意:
1、@property和@function.setter需要成对使用,如下
@property
def function_name
@function.setter
def function_name(self, attribute)
2、如果变量属性值和方法属性值相同,那么以下情况下是无法完成初始化函数 __init__ 中的赋值操作的,即无法初始化对象
代码演示2
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ ='shouke'
classTester(object):
def__init__(self, name, sex, title):
self.name = name
self.sex = sex
self.title = title
@property
defname(self):
returnself.name
@property
defsex(self):
return self.sex
@property
deftitle(self):
returnself.title
@title.setter
deftitle(self,title):
self.title =title
if__name__ =='__main__':
tester = Tester('shouke','M','Tester')
print(tester.title)
"D:\Program Files\python33\python.exe" E:/Projects/untitled/py1.py
Traceback (most recent call last):
File "E:/Projects/untitled/py1.py", line 30, in
tester = Tester('shouke', 'M', 'Tester')
File "E:/Projects/untitled/py1.py", line 8, in __init__
self.name = name
AttributeError: can't set attribute