参考:@property

NOTE

1.在绑定参数时,为了避免对属性不符合逻辑的操作,需要对传入的参数进行审核。

#!/usr/bin/env python3

class MyClass(object):
"""docstring for MyClass"""
def __init__(self):
super(MyClass, self).__init__() def set_Attr(self, score):
if score >= 0 and score <= 100:
self.score = score
else:
raise ValueError('Attribute Setting Error') def get_Attr(self):
return self.score def main():
A = MyClass()
A.score = 59
print(A.get_Attr()) A.set_Attr(101)
print(A.get_Attr()) if __name__ == '__main__':
main()
59
Traceback (most recent call last):
File "./oop9.py", line 26, in <module>
main()
File "./oop9.py", line 22, in main
A.set_Attr(101)
File "./oop9.py", line 12, in set_Attr
raise ValueError('Attribute Setting Error')
ValueError: Attribute Setting Error

普通的做法是,调用对象的方法传入参数并设置,但是这样看上去又过于繁琐。

2.Python内置的@property装饰器负责把一个方法变成属性进行调用:

class Student(object):
"""docstring for Student"""
def __init__(self):
super(Student, self).__init__() @property
def score(self): # turn into an attribute
return self.score @score.setter
def score(self, val):
if val >= 0 and val <= 100:
self.score = val
else:
raise ValueError('Attribute Setting Error')
RecursionError: maximum recursion depth exceeded in comparison

把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值。

getter => Attribute => create setter

3.还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性:

class Student(object):
"""docstring for Student"""
def __init__(self):
super(Student, self).__init__() @property
def score(self): # turn into an attribute
return self.score

此时Attribute score就是一个只读属性。无法对其进行设置或赋值。

2017/3/3

Python学习札记(三十七) 面向对象编程 Object Oriented Program 8 @property的更多相关文章

  1. Python学习札记(三十) 面向对象编程 Object Oriented Program 1

    参考:OOP NOTE 1.面向对象编程--Object Oriented Programming,简称OOP,是一种程序设计思想.OOP把对象作为程序的基本单元,一个对象包含了数据和操作数据的函数. ...

  2. Python学习札记(三十三) 面向对象编程 Object Oriented Program 4

    参考:继承和多态 NOTE 著名的开闭原则: 对扩展开放:允许新增Animal子类: 对修改封闭:不需要修改依赖Animal类型的Animal_func()等函数. 1.eg. #!/usr/bin/ ...

  3. Python学习札记(三十一) 面向对象编程 Object Oriented Program 2

    参考:类和实例 注意理解第七点. NOTE: 1.类是抽象的模板,比如Student类,实例是根据类创建出来的一个个具体的"对象",每个对象都拥有相同的方法,但各自的数据可能不同. ...

  4. Python学习札记(四十) 面向对象编程 Object Oriented Program 11

    参考:使用元类 NOTE: type() 1.type()函数可以用于检查一个类或者变量的类型. #!/usr/bin/env python3 class Myclass(object): " ...

  5. Python学习-第三天-面向对象编程基础

    Python学习-第三天-面向对象编程基础 类和对象 简单的说,类是对象的蓝图和模板,而对象是类的实例.这个解释虽然有点像用概念在解释概念,但是从这句话我们至少可以看出,类是抽象的概念,而对象是具体的 ...

  6. Python学习札记(三十四) 面向对象编程 Object Oriented Program 5

    参考:获取对象信息 NOTE 1.type()函数可以用来判断对象的类型: >>> type(123) <class 'int'> >>> type(' ...

  7. Python学习札记(三十八) 面向对象编程 Object Oriented Program 9

    参考:多重继承 NOTE #!/usr/bin/env python3 class Animal(object): def __init__(self, name): self.name = name ...

  8. Python学习札记(三十六) 面向对象编程 Object Oriented Program 7 __slots__

    参考:slots NOTE 1.动态语言灵活绑定属性及方法. #!/usr/bin/env python3 class MyClass(object): def __init__(self): pas ...

  9. Python学习札记(三十五) 面向对象编程 Object Oriented Program 6

    参考:实例属性和类属性 NOTE Python是动态语言,根据类创建的实例可以任意绑定属性. class Student(object): def __init__(self, name): self ...

随机推荐

  1. EasyUI DataGrid 时间格式化、字符串长度截取

    需要格式化日期时间和标题的方法,显示如下: 日期:2017-03-03 时间:2017-03-0 11:11 标题:标题名称 <table id="tbList" style ...

  2. ZOJ 3209 Treasure Map(精确覆盖)

    Treasure Map Time Limit: 2 Seconds      Memory Limit: 32768 KB Your boss once had got many copies of ...

  3. android的一些类库的优缺点

    经过本人的面试经验,以及接触的android项目,总结了一下android的一些类库的优缺点: 一,线程方面 1.AsyncTask 首先是线程优化以及缺陷方面,针对目前大多数类库来说,都有好的设计方 ...

  4. nginx + ngx_lua安装测试

    nginx lua模块淘宝开发的nginx第三方模块,它能将lua语言嵌入到nginx配置中,从而使用lua就极大增强了nginx的能力.nginx以高并发而知名,lua脚本轻便,两者的搭配堪称完美. ...

  5. mysql 数据操作 单表查询 concat()函数 定义显示格式

    #定义显示格式 concat() 函数用于连接字符串 类似于python 格式化操作print("姓名:%s" % name)或者 用,拼接一个一个的变量print("a ...

  6. 【开发者笔记】利用ab命令对接口进行压力测试

    目标:对接口进行正确性测试和压力测试 工具:Apache-ab 下载 系统:Windows.linux 目标接口:http://www.stagebo.xyz/foru/lifemonths 命令:a ...

  7. Spark checkpoint机制简述

    本文主要简述spark checkpoint机制,快速把握checkpoint机制的来龙去脉,至于源码可以参考我的下一篇文章. 1.Spark core的checkpoint 1)为什么checkpo ...

  8. [py][mx]django实现根据城市和课程机构类别过滤

    实现根据城市&课程机构过滤 实现点谁谁高亮,支持取交集. 直接上代码吧 本质上是过滤,多层过滤,取交集 def get(self, request): all_orgs = CourseOrg ...

  9. Centos7 Zabbix3.2安装

    实验环境: 阿里云 [zabbix@miyan ~]$ cat /etc/redhat-release CentOS Linux release (Core) 不得不说,官方文档确实强大 1.官方文档 ...

  10. redis客户端hiredis

    Hiredis 在官网 http://redis.io/clients 中有说明This is the official C client. Support for the whole command ...