广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python使用@property @x
  • 407
分享到

python使用@property @x

pythonproperty 2023-01-31 05:01:07 407人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

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

@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('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=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
{}

(完)



--结束END--

本文标题: python使用@property @x

本文链接: https://www.lsjlt.com/news/188385.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python使用@property @x
    @property可以将python定义的函数“当做”属性访问,从而提供更加友好访问方式,但是有时候setter/deleter也是需要的。 1》只...
    99+
    2023-01-31
    python property
  • Python的@property的使用
    目录1、几个概念2、举个例子3、解决问题4、换个方法通常,当我们需要对对象的敏感属性或者不希望外部直接访问的属性进行私有化,但是某些时候我们又需要对这些私有属性进行修改,该怎么处理呢...
    99+
    2022-11-12
  • python中@property怎么使用
    本篇内容介绍了“python中@property怎么使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!1.什么是property简单地说就是...
    99+
    2023-07-02
  • property如何在python中使用
    这篇文章给大家介绍property如何在python中使用,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。什么是property装饰器顾名思义,这是一个装饰器,起到一个辅助作用,具体理解请看下面一个例子。我们知道,程序中...
    99+
    2023-06-14
  • python @property用法作用
    @property广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性。详见链接:廖雪峰python3使用@property练习请利用@property给一个Screen对象加...
    99+
    2023-01-31
    作用 python property
  • python property的使用技巧分享
    property属性 一种用起来像是使用实例属性一样的特殊属性,可以对应于某个方法 既要保护类的封装特性,又要让开发者可以使用 对象.属性 的方式操作方法,@property 装饰器,可以直接通过方法名来访问方...
    99+
    2022-06-02
    python property
  • python中@Property属性使用方法
    目录一、前言二、创建用于计算的属性三、为属性添加安全保护机制一、前言 本文介绍的属性与类属性和实例属性不同。类属性和实例属性介绍的属性将返回所存储的值。而本文要介绍的属性是一种特殊的...
    99+
    2022-11-11
  • python @property 装饰器使用方法
    目录一、property的装饰器用法二、举例说明1.不用setter和getter方法的实现2.使用setter和getter的实现,增加温度值输入的限制3.利用property装饰...
    99+
    2022-11-13
  • python中@Property属性如何使用
    这篇文章主要介绍“python中@Property属性如何使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“python中@Property属性如何使用”文章能帮助大家解决问题。一、前言本文介绍的属...
    99+
    2023-07-02
  • property()函数如何在Python中使用
    这篇文章将为大家详细讲解有关 property()函数如何在Python中使用,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。python是什么意思Python是一种跨平台的、具有解释性、编译...
    99+
    2023-06-14
  • Python装饰器中@property使用详解
    目录最初的声明方式使用装饰器的声明方式使用装饰器的调用过程总结最初的声明方式 在没有@property修饰的情况下,需要分别声明get、set、delete函数,然后初始化prope...
    99+
    2022-11-13
  • Mac OS X 使用python ur
    今天是我第一次使用python的urllib.request.openurl 功能获取网页信息,代码如下 # 获取网络文件from urllib.request import urlopenwith urlopen(url='https:...
    99+
    2023-01-30
    OS Mac ur
  • Python中property标签属性怎么使用
    在Python中,可以使用@property装饰器来定义一个属性的getter方法,并使用@property.setter装饰器来定...
    99+
    2023-09-16
    Python
  • Python property装饰器使用案例介绍
    目录1.property2.property属性定义的两种方式3.案例1.property 装饰器:装饰器是在不修改被装饰对象源代码以及调用方式的前提下为被装饰对象添加新功能的可调用...
    99+
    2022-11-11
  • Python中关于property使用的小技巧
    目录property属性具体实例property属性的有两种方式装饰器方式旧式类新式类类属性方式property对象与@property装饰器对比property对象类属性@prop...
    99+
    2022-11-12
  • 如何在Python中使用@property装饰器
    这期内容当中小编将会给大家带来有关如何在Python中使用@property装饰器,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。一、property() 函数讲解了解 @property 装饰器之前,我们...
    99+
    2023-06-15
  • python装饰器property和setter怎么使用
    本篇内容介绍了“python装饰器property和setter怎么使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!1.引子:函数也是对象...
    99+
    2023-07-02
  • python中property装饰器的使用方法
    这篇文章主要介绍python中property装饰器的使用方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!python的数据类型有哪些python的数据类型:1. 数字类型,包括int(整型)、long(长整型)和...
    99+
    2023-06-15
  • python中的[1:]、[::-1]、X[:,m:n]和X[1,:]的使用
    目录Python中的[1:]Python中的[::-1]Python中的X[:,m:n]和X[1,:]Python中的[1:] 意思是去掉列表中第一个元素(下标为0),去后面的元素进...
    99+
    2022-11-11
  • python笔记之3.x与2.x的使用区
    python目前有两个分支:2.7.3和3.3.0,基本用法大同小异,但在个别细节上还是有出入的,具体看python.org网站。 个人感觉的差异有: 1、py3默认就是unicode,终于在写程序时可以不用再考虑中文...
    99+
    2023-01-31
    笔记 python
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作