@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. Oracle 11g服务详细介绍

    按照windows 7 64位 安装oracle 11g R2中的方法成功安装Oracle 11g后,共有7个服务,这七个服务的含义分别为: 1. Oracle ORCL VSS Writer Ser ...

  2. 用xaml画的带阴影3D感的圆球

    <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center"> <E ...

  3. Python 随笔之Redis

    Python学习记录 ——redis 2018-03-07 Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API.从 ...

  4. hbase查询基于标准sql规范中间件Phoenix

    Phoenix是个很好的hbase 查询工具,在hbase中安装也很简单,可以按照 http://www.cnblogs.com/laov/p/4137136.html 这个连接中进行配置客户端和服务 ...

  5. mongostat查看mongodb运行状态使用命令介绍

    mongostat是mongodb自带的一个用来查看mongodb运行状态的工具 使用说明 mongostat -h   字段说明 启用后的状况是这样的 insert query update del ...

  6. 启动Jmeter时遇到的几种错误

    1.权限不够 解决办法:用管理员权限运行 2.sdk版本太低 解决办法:1)查看当前sdk版本:java -version 2)安装sdk1.7或以上版本(jmeter3.0版本要用sdk1.7及以上 ...

  7. C++手写快读详解(快速读入数字)

    众所周知,C++里是自带读入的(这不废话吗) 例如: int a; cin>>a; 这样的读入理解简单,适合初学者,但是非常慢. 再例如: int a; scanf("%d&qu ...

  8. I am too vegetable to all kill the 51nod problems on level 2 and 3.

    51nod level 2:50/51 剩的一个题是切比雪夫距离转曼哈顿距离,现学的,bzoj3710过了,51nod上全wa了,很迷,可能有坑⑧. level 3:62/68 之前有的题有思路但是不 ...

  9. (76)zabbix_agentd.conf配置文件详解

    ############ GENERAL PARAMETERS ################# ### Option: PidFile# Name of PID file.# Agent PID文 ...

  10. 4.在Cisco Packet Tracerl里路由器密码重置

    在路由器的特权模式的密码忘记的情况下,关闭路由器的电源,在接通电源,在路由器载入的时候,按ctrl+c,直接进入monitor模式 输入:confreg 0x2142 reset 重新进入后 enab ...