@property可以将python定义的函数“当做”属性访问,从而提供更加友好访问方式,但是有时候setter/deleter也是需要的。
1》只有@property表示只读。
2》同时有@property和@x.setter表示可读可写。

3》同时有@property和@x.setter和@x.deleter表示可读可写可删除。

class student(object): #新式类
def __init__(self,id):
self.__id=id
@property #读
def score(self):
return self._score
@score.setter #写
def score(self,value):
if not isinstance(value,int):
raise ValueError('score must be an integer!')
if value<0 or value>100:
raise ValueError('score must between 0 and 100')
self._score=value
@property #读(只能读,不能写)
def get_id(self):
return self.__id s=student('')
s.score=60 #写
print s.score #读
#s.score=-2 #ValueError: score must between 0 and 100
#s.score=32.6 #ValueError: score must be an integer!
s.score=100 #写
print s.score #读
print s.get_id #读(只能读,不可写)
#s.get_id=456 #只能读,不可写:AttributeError: can't set attribute

运行结果:
60
100
123456

class A(object):#新式类(继承自object类)
def __init__(self):
self.__name=None
def getName(self):
return self.__name
def setName(self,value):
self.__name=value
def delName(self):
del self.__name
name=property(getName,setName,delName) a=A()
print a.name #读
a.name='python' #写
print a.name #读
del a.name #删除
#print a.name #a.name已经被删除 AttributeError: 'A' object has no attribute '_A__name'

运行结果:
None
python

class A(object):#要求继承object
def __init__(self):
self.__name=None #下面开始定义属性,3个函数的名字要一样!
@property #读
def name(self):
return self.__name
@name.setter #写
def name(self,value):
self.__name=value
@name.deleter #删除
def name(self):
del self.__name a=A()
print a.name #读
a.name='python' #写
print a.name #读
del a.name #删除
#print a.name # a.name已经被删除 AttributeError: 'A' object has no attribute '_A__name'

运行结果:
None
python

class person(object):
def __init__(self,first_name,last_name):
self.first_name=first_name
self.last_name=last_name
@property #读
def full_name(self):
return '%s %s' % (self.first_name,self.last_name) p=person('wu','song')
print p.full_name #读
#p.full_name='song ming' #只读,不可修改 AttributeError: can't set attribute
p.first_name='zhang'
print p.full_name #读

运行结果:

wu song
zhang song
上面都是以新式类为例子,下面我们看一个包含经典类的例子:

#!/usr/bin/env python
#coding:utf-8 class test1:#经典类:没有继承object
def __init__(self):
self.__private='alex 1' #私有属性以2个下划线开头
#读私有属性
@property
def private(self):
return self.__private
#尝试去写私有属性(对于经典类而言,“写”是做不到的,注意看后边的代码和注释!)
@private.setter
def private(self,value):
self.__private=value
#尝试去删除私有属性(对于经典类而言,“删除”也是做不到的,具体看后边的代码和注释!)
@private.deleter
def private(self):
del self.__private class test2(object):#新式类:继承了object
def __init__(self):
self.__private='alex 2' #私有属性以2个下划线开头
#读私有属性
@property
def private(self):
return self.__private
#写私有属性
@private.setter
def private(self,value):
self.__private=value
#删除私有属性
@private.deleter
def private(self):
del self.__private t1=test1()
#print t1.__private #外界不可直接访问私有属性
print t1.private #读私有属性
print t1.__dict__
t1.private='change 1' #对于经典类来说,该语句实际上是为实例t1添加了一个实例变量private
print t1.__dict__
print t1.private #输出刚刚添加的实例变量private
t1.private='change 2'
print t1.__dict__
del t1.private #删除刚刚添加的实例变量private
print t1.__dict__
print t1.private #读私有属性
#del t1.private #无法通过这种方式删除私有属性:AttributeError: test1 instance has no attribute 'private'
#对于经典类而言,我们无法通过上面的语句,对实例的私有变量__private进行修改或删除!
print '-------------------------------------------------------'
t2=test2()
print t2.__dict__
print t2.private #继承了object,添加@private.setter后,才可以写
t2.private='change 2' #修改私有属性
print t2.__dict__
print t2.private
del t2.private #删除私有变量
#print t2.private #私有变量已经被删除,执行“读”操作会报错:AttributeError: 'test2' object has no attribute '_test2__private'
print t2.__dict__
#对于新式类而言,我们可以通过上面的语句,对实例的私有变量__private进行修改或删除

运行结果: 

alex 1
{'_test1__private': 'alex 1'}
{'_test1__private': 'alex 1', 'private': 'change 1'}
change 1
{'_test1__private': 'alex 1', 'private': 'change 2'}
{'_test1__private': 'alex 1'}
alex 1
-------------------------------------------------------
{'_test2__private': 'alex 2'}
alex 2
{'_test2__private': 'change 2'}
change 2
{}

---------------------

本文来自 快递小可 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/sxingming/article/details/52916249?utm_source=copy

python使用@property @x.setter @x.deleter的更多相关文章

  1. python基础-abstractmethod、__属性、property、setter、deleter、classmethod、staticmethod

    python基础-abstractmethod.__属性.property.setter.deleter.classmethod.staticmethod

  2. 封装,封装的原理,Property ,setter ,deleter,多态,内置函数 ,__str__ , __del__,反射,动态导入模块

    1,封装 ## 什么是封装 what 对外隐藏内部的属性,以及实现细节,并给外部提供使用的接口 学习封装的目的:就是为了能够限制外界对内部数据的方法 注意 :封装有隐藏的意思,但不是单纯的隐藏 pyt ...

  3. python中property和setter装饰器

    property和setter装饰器 作用:调用方法改为调用对象, 比如 : p.set_name()     改为   p.set_name 区别:  前者改变get方法,后者改变set方法 效果图 ...

  4. 第7.26节 Python中的@property装饰器定义属性访问方法getter、setter、deleter 详解

    第7.26节 Python中的@property装饰器定义属性访问方法getter.setter.deleter 详解 一.    引言 Python中的装饰器在前面接触过,老猿还没有深入展开介绍装饰 ...

  5. python 中 property 属性的讲解及应用

    Python中property属性的功能是:property属性内部进行一系列的逻辑计算,最终将计算结果返回 property属性的有两种方式: 1. 装饰器 即:在方法上应用装饰器 2. 类属性 即 ...

  6. 【转】python之property属性

    1. 什么是property属性 一种用起来像是使用的实例属性一样的特殊属性,可以对应于某个方法 # ############### 定义 ############### class Foo: def ...

  7. python中property属性的介绍及其应用

    Python的property属性的功能是:property属性内部进行一系列的逻辑计算,最终将计算结果返回. 使用property修饰的实例方法被调用时,可以把它当做实例属性一样 property的 ...

  8. Python使用property函数定义的属性名与其他实例变量重名会怎么样?

    首先如果定义的属性名与该属性对应的操作方法操作的实例对象同名就会触发无穷的递归调用,相关部分请参考<Python案例详解:使用property函数定义与实例变量同名的属性会怎样?> 但如果 ...

  9. Python使用property函数定义属性访问方法如果不定义fget会怎么样?

    我们知道Python使用property函数定义属性访问方法时的语法如下: 实例属性=property(fget=None, fset=None, fdel=None, doc=None) 而是要@p ...

随机推荐

  1. UICollectionView基础API笔记

    UICollectionView系列API,属性含义笔记.在UICollectionView笔记1中我们了解了UICollectionView是什么,以及可以做什么:在UICollectionView ...

  2. vue使用element-ui实现按需引入

    基于Vue的Ui框架 饿了么公司基于vue开的的vue的Ui组件库 Element Ui 基于vue pc端的UI框架 MintUi 基于vue 移动端的ui框架 http://element.ele ...

  3. 使用tooltip显示jquery.validate.unobtrusive验证信息

    通过重写CSS实现使用tooltip显示jquery.validate.unobtrusive验证信息,效果如图: 1. 在ViewModel中定义验证规则 [Display(Name = " ...

  4. Django Form 表单

    Form 表单功能 生成HTML表单元素检查表单元素的合法性验证如果错误,重复显示表单数据类型转换 Form相关的对象 Widget 渲染成HTML元素的工具Field Form对象中的一个字段For ...

  5. Python基础总结与实践

    Python简介 Python是一种动态解释型编程语言,在模块载入时将源码编译成字节码, 这些字节码被虚拟机PVM解释执行,其中解释执行是Python性能较低的主要原因: Python使用C语言编写, ...

  6. 爬虫爬取代理IP池及代理IP的验证

    最近项目内容需要引入代理IP去爬取内容. 为了项目持续运行,需要不断构造.维护.验证代理IP. 为了绕过服务端对IP 和 频率的限制,为了阻止服务端获取真正的主机IP. 一.服务器如何获取客户端IP ...

  7. hdu-3549 Flow Problem---最大流模板题(dinic算法模板)

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=3549 题目大意: 给有向图,求1-n的最大流 解题思路: 直接套模板,注意有重边 传送门:网络流入门 ...

  8. Exceptions and Errors on iOS

    异常:程序缺陷导致:不可恢复:给开发者使用: 错误:资源受限导致:可恢复:提示给用户. https://blog.jayway.com/2010/10/13/exceptions-and-errors ...

  9. c++连接mysql并提示“无法解析的外部符号 _mysql_server_init@12”解决方法&提示缺少“libmysql.dll”

    课程作业要用c++连接mysql server,但是出现些小问题,经查阅资料已经解决,做一下笔记. 环境:vs2017, mysql版本是8.0.16-winx64. 设置项目属性   项目 -  C ...

  10. 深入理解计算机系统_3e 第十一章家庭作业 CS:APP3e chapter 11 homework

    注:tiny.c csapp.c csapp.h等示例代码均可在Code Examples获取 11.6 A. 书上写的示例代码已经完成了大部分工作:doit函数中的printf("%s&q ...