Python3之使用@property
在绑定属性时,如果我们直接把属性暴露出去,虽然写起来简单,但是,没有办法检查参数,导致可以把成绩随便改
>>> class Student(object):
... pass
...
>>> s=Student()
>>> s.score=999
>>> s.score
999
>>> s.score='abc'
>>> s.score
'abc'
这显然不会逻辑,为了现在score的范围可以,通过一个set_score()方法,同通过一个get_score()来获取成绩,这样,在set_score()方法里,就可以检查参数:
class Student(object):
def get_score(self):
return self._score
def set_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~100!')
self._score=value
现在,对人员的Student实例进行操,就不能随心所欲地设置score了
>>> s.set_score(100)
>>> s.get_score()
100
>>> s.set_score(101)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in set_score
ValueError: score must between 0~100!
但是,上面的调用方法比较复杂,有没有直接用属性这么直接减掉
有没有既能检查参数,又可以有类似属性这样的简单方式来访问类的变量呢。对于类的方法,装饰器一样起作用。python内置的@property装饰器就是负责把一个方法变成属性调用的:
class Student(object):
@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~100!')
self._score=value
@property的实现比较复杂,这里看如何使用。把一个getter的方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器,负责把一个setter方法变成属性赋值,于是我们就拥有了一个可控的属性操作:
>>> s=Student()
>>> s.score=100
>>> s.score
100
>>> s.score=101
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 18, in score
ValueError: score must between 0~100!
注意到这个神奇的@property,我们再对实例属性操作的时候,就知道该属性很可能不是直接暴露的,而是通过getter和setter方法来实现的。
还可以只定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性
class Student(object):
#出生年格式为2001
@property
def birth(self):
return self._birth
@birth.setter
def birth(self,value):
self._birth=value
#年龄age定义为只读即没有setter属性
@property
def age(self):
return 2019-self._birth
操作
>>> s=Student()
>>> s.birth=2000
#age是根据birth用2019-birth计算出来的
>>> s.age
19
#直接修改age因为没有定义setter使用报错
>>> s.age=20
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
练习
利用@property给一个Screen对手加上width和heigth属性,已经一个只读属性resolution Screen.py
class Screen(object):
#设置长
@property
def width(self):
return self._width
#检查输入是否规范必须是int并且大于0
@width.setter
def width(self,value):
if not isinstance(value,int):
raise ValueError('width must be an integer!')
if value < 0:
raise ValueError('width must > 0')
self._width=value
#设置高
@property
def height(self):
return self._height
@height.setter
def height(self,value):
if not isinstance(value,int):
raise ValueError('height must be an integer!')
if value < 0:
raise ValueError('height must > 0')
self._height=value
#面积只设置getter方法通过长乘高得到
@property
def resolution(self):
return self._width*self._height s=Screen()
s.width=1024
s.height=768
print(s.resolution)
Python3之使用@property的更多相关文章
- python3 封装之property 多态 绑定方法classmethod 与 非绑定方法 staticmethod
property 特性 什么是特性property property 是一种特殊的属性,访问它时会执行一段功能(函数),然后返回值 例如 BMI指数(bmi是计算而来的,但很明显它听起来像是一个属性而 ...
- python3与django中@property详解
django提供了内置装饰器 @staticmethod\@classmethod\property 在OSQA中,@property的使用频率是非常高的.下面就是它的使用方法: @property ...
- python3 - property的使用
传统的绑定属性值,会把属性暴露出去,而且无法检查参数是否合法,如下: class Test(object): def __int__(self,age): self.age = age 为了检查参数 ...
- python3 高级编程(三) 使用@property
@property装饰器就是负责把一个方法变成属性调用的. @property广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性 cl ...
- python3 速查参考- python基础 8 -> 面向对象基础:类的创建与基础使用,类属性,property、类方法、静态方法、常用知识点概念(封装、继承等等见下一章)
基础概念 1.速查笔记: #-- 最普通的类 class C1(C2, C3): spam = 42 # 数据属性 def __init__(self, name): # 函数属性:构造函数 self ...
- Python3.5-20190519-廖老师-自我笔记-面向对象中slots变量--@property的使用
python是动态语言,可以随时随地给实例对象添加属性和方法,但是我们想限制属性的名字,可以使用__slots__特殊变量来限制 使用__slots__要注意,__slots__定义的属性仅对当前类实 ...
- python3(二十七)property
""" """ __author__ = 'shaozhiqi' # 绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单, # 但是, ...
- python3 的setter方法及property修饰
#!/usr/bin/env pthon#coding:utf-8 class person(object): def __init__(self,name,sex,age,surface,heigh ...
- 也说python的类--基于python3.5
在面向对象的语言中,除了方法.对象,剩下的一大重点就是类了,从意义上来讲,类就是对具有相同行为对象的归纳.当一个或多个对象有相同属性.方法等共同特征的时候,我们就可以把它归纳到同一个类当中.在使用上来 ...
随机推荐
- Yarn 配置阿里源
1.查看一下当前源 yarn config get registry 2.切换为淘宝源 yarn config set registry https://registry.npm.taobao.org ...
- springboot启动时执行任务CommandLineRunner
# SpringBoot中CommandLineRunner的作用> 平常开发中有可能需要实现在项目启动后执行的功能,SpringBoot提供的一种简单的实现方案就是添加一个model并实现Co ...
- LOJ P10114 数星星 stars 题解
每日一题 day7 打卡 Analysis 树状数组 由于题目中给的数据是按y轴排序,我们只需构建x轴的树状数组,也就是说我们只需统计星星i之前一共有多少个x坐标小于或等于Xi的星星,这个数值也就是星 ...
- 内存原理与PHP的执行过程
一.内存结构 栈区:保存的是变量名(术语:引用),对于cpu来说,读写速度很快 堆区:存储“复杂”的数据,数组.对象.字符串(字符串比较特殊)等 数据段:又分为数据段全局区(用于存储简单的数据,如数字 ...
- 数据库学习之六--事务(Transaction)
一.定义 事务是指访问并可能更新数据库中各种数据项的一个程序执行单元(unit). 规则: 1. 用形如begin transaction和end transaction语句来界定 2. 由事务开始和 ...
- RS-232串口通信简介
1969年,美国电子工业协会将RS-232定为串行通信接口的电器标准,该标准定义了数据终端设备DTE(Date Teriminal Equipment)与数据通信设备DCE(Data Communic ...
- Other-Website-Contents.md
title: 本站目录 categories: Other sticky: 10 toc: true keywords: 机器学习基础 深度学习基础 人工智能数学知识 机器学习入门 date: 999 ...
- 【原创】go语言学习(二十二)网络编程
目录 TCP/IP协议介绍 GO快速实现TCP服务端 GO快速实现TCP客户端 UDP协议介绍 UDP编程实例 TCP/IP协议介绍 1.互联网起源 A. 起源于美国五角大楼,它的前身是美国国防部高级 ...
- 使用AwesomeWM作为Mate(Gnome相同) Desktop的窗口管理器
本文通过MetaWeblog自动发布,原文及更新链接:https://extendswind.top/posts/technical/using_awesomewm_as_wm_of_mate_des ...
- 使用jsonpath解析多层嵌套的json响应信息
Python自带的json库可以把请求转为字典格式, 但在多层嵌套的字典中取值往往要进行多次循环遍历才能取到相应的数据, 如: res_dict = { "code": 0, &q ...