Python学习随机(第二弹)
来源:互联网 发布:西门子ug软件侵权 编辑:程序博客网 时间:2024/06/08 11:13
1. property函数
在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,但是,没办法检查参数,导致可以把成绩随便改。为了限制属性的范围,可以通过一个setter
方法来设置属性,再通过一个getter
来获取属性,这样,在setter
方法里,就可以检查参数合理性,但是这样又略显复杂。那么,有没有一种简单的方法,可以实现书写简单有可以检查属性呢?
- 使用property([fget[, fset[, fdel[, doc ]]]])(私有变量)
class student: def __init__(self): self.__score = None def getscore(self): return self.__score def setscore(self,value): self.__score = value def delscore(self): del self.__score qscore = property(getscore,setscore,delscore,"I'm the 'score' property.")
stu = student()print 'student.score: %s' % stu.qscorestu.qscore = 80print 'student.score: %s' % stu.qscoredel stu.qscoreprint 'student.score: %s' % stu.qscore
可以通过stu.qscore的方式,对score属性进行取值和赋值操作了
- @property,@对象.setter
class teacher: def __init__(self): self.__score = None @property def score(self): return self.__score @score.setter def score(self,value): self.__score = value @score.deleter def score(self): del self.__scoretch = teacher()print 'teacher.score: %s' % tch.scoretch.score = 60print 'teacher.score: %s' % tch.scoredel tch.scoreprint 'teacher.score: %s' % tch.score
0 0
- Python学习随机(第二弹)
- python 随机库学习
- Python学习 随机数据生成器
- 学习Python第二天
- 学习第二天python
- Python 学习第二天
- Python学习第二天
- 学习python第二天
- 学习python第二天
- Python学习第二天
- python学习第二天
- 第二周学习Python
- python 学习第二天
- 学习python第二周
- python学习第二天
- 学习python第二天
- Python学习第二天
- Python学习第二篇
- Python转义字符
- 百万级数据查询优化之in
- 杭电2209 翻纸牌游戏 DFS BFS 搜索
- cocos-js,数据本地存储
- BCP 数据的导入和导出
- Python学习随机(第二弹)
- Leetcode学习(40)—— Valid Anagram
- 使用Ado.net执行SP很慢,而用SSMS执行很快
- CODEVS 4511 信息传递
- mac 下载编译Android源码
- JDK中的URLConnection参数详解
- 分布式架构学习之:006--构建Dubbo服务消费者Web应用的war包并在Tomcat中部署
- phoenix使用
- iOS添加启动页图片添加设置