python property setter_python使用@property @x.setter @x.deleter

本文介绍了Python中@property的使用,它可将函数“当做”属性访问。说明了只有@property表示只读,同时有@property和@x.setter表示可读可写,还有@x.deleter则表示可读可写可删除。通过多个新式类和经典类的示例代码,展示了不同情况下属性的读写和删除操作。
Python3.9

Python3.9

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

@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#读

defscore(self):returnself._score

@score.setter#写

defscore(self,value):if notisinstance(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#读(只能读,不能写)

defget_id(self):return self.__ids=student('123456')

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=NonedefgetName(self):return self.__name

defsetName(self,value):

self.__name=valuedefdelName(self):del self.__namename=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 #读

defname(self):return self.__name@name.setter#写

defname(self,value):

self.__name=value

@name.deleter#删除

defname(self):del self.__namea=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

classperson(object):def __init__(self,first_name,last_name):

self.first_name=first_name

self.last_name=last_name

@property#读

deffull_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个下划线开头

#读私有属性

@propertydefprivate(self):return self.__private

#尝试去写私有属性(对于经典类而言,“写”是做不到的,注意看后边的代码和注释!)

@private.setterdefprivate(self,value):

self.__private=value#尝试去删除私有属性(对于经典类而言,“删除”也是做不到的,具体看后边的代码和注释!)

@private.deleterdefprivate(self):del self.__private

class test2(object):#新式类:继承了object

def __init__(self):

self.__private='alex 2' #私有属性以2个下划线开头

#读私有属性

@propertydefprivate(self):return self.__private

#写私有属性

@private.setterdefprivate(self,value):

self.__private=value#删除私有属性

@private.deleterdefprivate(self):del self.__privatet1=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__

printt2.privatedel 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

{}

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

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

您可能感兴趣的与本文相关的镜像

Python3.9

Python3.9

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值