__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. iOS之网络编程

    发送HTTP请求的方法 在HTTP/1.1协议中,定义了8种发送http请求的方法 GET.POST.OPTIONS.HEAD.PUT.DELETE.TRACE.CONNECT.PATCH 根据HTT ...

  2. Openjudge-计算概论(A)-奥运奖牌计数

    描述: 2008年北京奥运会,A国的运动员参与了n天的决赛项目(1≤n≤17).现在要统计一下A国所获得的金.银.铜牌数目及总奖牌数. 输入输入n+1行,第1行是A国参与决赛项目的天数n,其后n行,每 ...

  3. java求阶乘

    //阶乘 public static int rec(int n){ if(n==1){ return 1; }else{ return n*rec(n-1); } }

  4. Cenots安装openvpn、pam_mysql进行用户认证和流量控制

    一.安装Centos6.5 二.修改YUM仓库 1. 默认仓库不能访问部分软件包,因此我们需要修改YUM仓库 cd /etc/yum.repos.d #备份 mv ./CentOS-Base.repo ...

  5. mysql、sqlserver数据库常见数据类型对应java中的的类型探究

    由于本次测试表的结构不涉及到主键的自增长,所以mysql.sqlserver建表语句相同: CREATE TABLE testType ( id INT NOT NULL DEFAULT 0, gen ...

  6. db2安装要设置tcp、ip

    1.注册表变量DB2COMM是否已经设置了值,是什么级别的?db2set -all | grep -i "DB2COMM" (in unix like os)db2set -all ...

  7. evernote

    evernote hebinn@163.com How to get Note Link Right Click Note & Copy Note Link Open Note : Note- ...

  8. bootstrap开始咯

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name ...

  9. 用shell获得hadoop中mapreduce任务运行结果的状态

    在近期的工作中,我需要用脚本来运行mapreduce,并且要判断运行的结果,根据结果来做下一步的动作. 开始我想到shell中获得上一条命令运行结果的方法,即判断"$?"的值 if ...

  10. innerhtml 和value值有什么区别

    value 值写在标签里面的,innerHTML写在<button type="button" onclick="myFunction()">Try ...