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):
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需要成對使用,如下
def function_name
@function.setter
def function_name(self, attribute)
2、如果變量屬性值和方法屬性值相同,那麼以下情況下是無法完成初始化函數 __init__ 中的指派操作的,即無法初始化對象
代碼示範2
#
-*- coding:utf-8 -*-
__author__
=
'shouke'
class
Tester(object):
def
__init__(self,
name, sex, title):
self.name
= name
self.sex
= sex
self.title
= title
@property
name(self):
return
self.name
sex(self):
self.sex
title(self):
self.title
@title.setter
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('shouke', 'M', 'Tester')
"E:/Projects/untitled/py1.py", line 8, in __init__
self.name
AttributeError: can't set attribute
作者:授客
QQ:1033553122
全國軟體測試QQ交流群:7156436
Git位址:https://gitee.com/ishouke
友情提示:限于時間倉促,文中可能存在錯誤,歡迎指正、評論!
作者五行缺錢,如果覺得文章對您有幫助,請掃描下邊的二維碼打賞作者,金額随意,您的支援将是我繼續創作的源動力,打賞後如有任何疑問,請聯系我!!!
微信打賞
支付寶打賞 全國軟體測試交流QQ群
