property使用简介
by:授客 QQ:1033553122
功能简介
1) 把类方法变成只读属性
2) setter和getter的另一种实现
代码演示1
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
class User(object):
def __init__(self, username, password):
self._username = username
self._password = password
@property
def username(self):
return self._username
@username.setter
def username(self, username):
self._username = username
@property
def password(self):
return self._password
@password.setter
def password(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'
class
Tester(object):
def
__init__(self,
name, sex, title):
self.name
= name
self.sex
= sex
self.title
= title
@property
def
name(self):
return
self.name
@property
def
sex(self):
return
self.sex
@property
def
title(self):
return
self.title
@title.setter
def
title(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