__slots__属性可以设置 允许被设置的属性

class Student:
__slots__ = ("name", "age")

>>> s = Student()

>>> s.age = 

>>> s.name = "Zoro"

>>> s.score =
Traceback (most recent call last):
File "<ipython-input-38-b5a9e82f869f>", line , in <module>
s.score = AttributeError: 'Student' object has no attribute 'score'

当一个类中设置__slots__属性时,只有()中的属性可以动态设置


@property装饰器

class Student():
@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 < or value > :
raise ValueError("Score must between 0~100!")
self._score = value @score.deleter
def score(self):
del self._score

>>> s = Student()
>>> s.score =
>>> s.score
Out[]: 100
>>> s.score =
Traceback (most recent call last):
File "<ipython-input-44-84f4bf77cd8e>", line , in <module>
s.score =
File "C:/Users/SQD/Desktop/@property.py", line , in score
raise ValueError("Score must between 0~100!")
ValueError: Score must between ~! >>> s.score = "abc"
Traceback (most recent call last):
File "<ipython-input-45-179a51b0c6cf>", line , in <module>
s.score = "abc"
File "C:/Users/SQD/Desktop/@property.py", line , in score
raise ValueError("Score must be an integer!")
ValueError: Score must be an integer! >>> del s.score

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

还可以设置只读属性:只有getter,没有setter

class Student:
@property
def birth(self):
return self._birth
@birth.setter
def birth(self, value):
self._birth = value @property
def age(self):
return - self._birth

>>> s = Student()
>>> s.birth =
>>> s.age
Out[]: >>> s.age =
Traceback (most recent call last):
File "<ipython-input-58-03895bf010a3>", line , in <module>
s.age = AttributeError: can't set attribute

Python -- OOP高级 -- __slots__、@property的更多相关文章

  1. Python面向对象高级编程-@property

    使用@property 在绑定属性时,如果直接把属性暴露出去,虽然写起来简单,但是没法检查参数,导致可以把成绩随便改: >>> class Student(object): pass ...

  2. python面向对象高级:@property

    @property 把方法『变成』了属性,广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性. 最大的作用就是既能检查参数,又可以用类 ...

  3. Python -- OOP高级 -- 元类

    type()函数既可以返回一个对象的类型,又可以创建出新的类型 def fn(self, name="world"): print("Hello, %s!" % ...

  4. Python -- OOP高级 -- 定制类

    __str__ 和 __repr__ :实例对象直接显示字符串 class Student: def __init__(self, name): self.name = name def __str_ ...

  5. Python -- OOP高级 -- 枚举类

    Enum可以把一组相关常量定义在一个class中,且class不可变,而且成员可以直接比较. from enum import Enum Month = Enum('Month', ('Jan', ' ...

  6. Python OOP(1):从基础开始

    本文旨在Python复习和总结: 1.如何创建类和实例? # 创建类 class ClassName(object): """docstring for ClassNam ...

  7. <转>Python OOP(1):从基础开始

    转自  http://www.cnblogs.com/BeginMan/p/3510786.html 本文旨在Python复习和总结: 1.如何创建类和实例? # 创建类 class ClassNam ...

  8. Python---14面向对象高级编程(__slots__&@property)

    一.使用__slots__ 正常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性.先定义class: class Stude ...

  9. Python——详解__slots__,property和私有方法

    本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是Python专题的第11篇文章,我们来聊聊面向对象的一些进阶使用. __slots__ 如果你看过github当中一些大牛的代码,你会 ...

随机推荐

  1. chapter8_4 错误处理

    在Lua中,对于大多数程序都不用作任何错误处理,应用程序本身会负责这类问题. 所有的Lua活动都是由应用程序的一次调用开始的,这类调用要求Lua执行一个程序块. 执行过程中发生了错误,此调用会返回一个 ...

  2. Chapter7 迭代器

    结合泛型for的所有功能,写出更加简单,高效的迭代器. 1.迭代器和closure 迭代器是一种可以遍历集合中所有元素的机制.在Lua中用函数去表示它. 每调用一次,就返回下一个元素. 迭代器在两次成 ...

  3. MyBatisNet 学习

    SQL Maps Sql Maps是这个框架中最激动人心的部分,它是整个iBATIS Database Layer的核心价值所在.通过使用Sql Maps你可以显著的节约数据库操作的代码量.SQL M ...

  4. JS全选

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"% ...

  5. webservice 尝试加载 Oracle 客户端库时引发 BadImageFormatException。如果在安装 32 位 Oracle 客户端组件的情况下运行,将出现此问题

    最近做的项目中,应用服务器迁移到另外一台服务器,操作系统升级为win10,配置好IIS里的应用程序发布网站和Webservice网站后, 客户端程序调用Webservice出错: “尝试加载 Orac ...

  6. 学习笔记——解释器模式Interpreter

    解释器模式,其实就是编译原理中的语法解释器,如果用在项目中,可以用于实现动态脚本的解析,也就是说项目可以支持用户脚本扩展. 但实际上,这种运行时解释,效率很慢,如果不是很需要的话,不建议使用. 一种简 ...

  7. java se 另一博客

    http://blog.csdn.net/terryzero/article/category/517680

  8. hdu_5690_All X(找循环节)

    题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=5690 题意: Problem Description F(x, m)F(x,m) 代表一个全是由数字x ...

  9. C++ 中 const和define的区别

    来源网址:http://wujiangping.blog.163.com/blog/static/195182011201255115125205/ 请区别用#define命令定义的符号常量和用con ...

  10. why TCP guarentee delivery?

    Simple idea: just use a TIMEOUT, if no answer after a certain seconds, just re-deliver!