天天看点

Python property使用简介

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群  

Python property使用简介
Python property使用简介
Python property使用简介