__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. redhat 时区修改

    修改系统时区,发现只需要一个命令就可以解决 修改之前: cp /usr/share/zoneinfo/Asia/Chongqing  /etc/localtime 修改之后:

  2. 洛谷-火柴棒等式-NOIP2008提高组复赛

    题目描述 Description 给你n根火柴棍,你可以拼出多少个形如“A+B=C”的等式?等式中的A.B.C是用火柴棍拼出的整数(若该数非零,则最高位不能是0).用火柴棍拼数字0-9的拼法如图所示: ...

  3. Openjudge-计算概论(A)-能被3,5,7整除的数

    描述: 输入一个整数,判断它能否被3,5,7整除,并输出以下信息:1.能同时被3,5,7整除(直接输出3 5 7,每个数中间一个空格):2.能被其中两个数整除(输出两个数,小的在前,大的在后.例如:3 ...

  4. manifest中的largeHeap是干什么用的?

    转 http://blog.csdn.net/jiaoyang623/article/details/8773445 今天群里有人讨论怎么给app分配超过100M的内存,有人亮出了largeHeap参 ...

  5. js预编译

    先来做三个测试 eg1: var a; a = 1; function a() {}; console.log(a); eg2: var a; function a() {}; console.log ...

  6. TextView赋值int型,并显示

    textview赋值int型采用text.setText(FPS+""); FPS为int型变量 或者在thread线程需要在主Activity中显示文字,可以调用: runOnU ...

  7. UVALive - 3026 Period kmp next数组的应用

    input n 2<=n<=1000000 长度为n的字符串,只含小写字母 output Test case #cas 长度为i时的最小循环串 循环次数(>1) 若没有则不输出 做法 ...

  8. 《JavaScript高级程序设计》读书笔记 ---语句

    do-while语句do-while 语句是一种后测试循环语句,即只有在循环体中的代码执行之后,才会测试出口条件.换句话说,在对条件表达式求值之前,循环体内的代码至少会被执行一次.以下是do-whil ...

  9. InvalidateRect只是增加重绘区域,在下次WM_PAINT的时候才生效

    emWIN里面的无效重绘和windows很类似. WM_InvalidateArea()和WM_InvalidateRect()只重绘指定的区域,其他区域不会重绘,这样避免了闪烁,重绘发生在下次WM_ ...

  10. DLL调试方法

    1.已经做好的dll不能设置:你可以用AfxMessageBox把信息打印出来.2.哪个地方调用的函数 把DLL重新编译一次 在把DLL放到工程里 从新添加一下 然后在你工程调用DLL内容的地方设置断 ...