__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. 表单提交是ajax提交,PC提交没问题但是手机提交就会一直跳到error,并且也没状态码一直是0

    真是被自己蠢死了button标签他会自动提交刷新页面 <form id="baoming_from"> <p>请填写您的个人信息</p> < ...

  2. 生成SQL脚本的方法

    2点需要注意的关键: (1)选择特定数据库对象不包含用户选项: (2)要编写脚本的数据的类型选择"架构和数据".

  3. 五、oracle 表的管理

    一.表名和列名的命名规则1).必须以字母开头2).长度不能超过30个字符3).不能使用oracle的保留字4).只能使用如下字符 a-z,a-z,0-9,$,#等 二.数据类型1).字符类char 长 ...

  4. IIS:错误: 无法提交配置更改,因为文件已在磁盘上更改

    文件名: \\?\C:\Windows\system32\inetsrv\config\applicationHost.config 错误: 无法提交配置更改,因为文件已在磁盘上更改 通过 Micro ...

  5. Android 面试题(转)

    转自:http://www.jobui.com/mianshiti/it/android/2682/ 1. Android dvm的进程和Linux的进程, 应用程序的进程是否为同一个概念DVM指da ...

  6. Java語言

    Java编程语言是个简单.完全面向对象.分布式.解释性.健壮.安全与系统无关.可移植.高性能.多线程和动态的编程语言. Java可以撰写跨平台应用软件,是有Sun Microsystems公司于199 ...

  7. ieee80211_rx

    ieee80211rx.c(E:\code\linux\net\ieee80211) 所有接收到的帧都送到这个函数中去 int ieee80211_rx(struct ieee80211_device ...

  8. Django: 之用户注册、缓存和静态网页

    Django 用户注册系统 Django 的源码中已经有登录,退出,重设密码等相关的视图函数,在下面这个app中 django.contrib.auth 可以点击对应的版本查看相关源代码:1.9  1 ...

  9. how to stop a thread

    it seems all stop methods of thread have been deprecated by java. so how to stop a thread then? it i ...

  10. 【jsp 防盗链】Referer的简单使用

    在web系统中,盗链的问题时有发生,即复制一个url地址,在另一个地方也能访问. 在jsp中通过request对象可以获取客户请求信息和表单信息,在客户请求头信息中,"Referer&quo ...