用描述符复用property

前端之家收集整理的这篇文章主要介绍了用描述符复用property前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

重点是复用
要感受它。


-- coding:utf-8 --

from weakref import WeakKeyDictionary

class Grade(object):
def init(self):
self._values = WeakKeyDictionary()

def __get__(self,instance,instance_type):
    if instance is None:
        return None
    return self._values.get(instance,0)

def __set__(self,value):
    if not ( 0<=value<=100):
        raise ValueError("Grade must be in 0 .. 100")
    self._values[instance] = value

class Student(object):
cn = Grade()
en = Grade()

p1 = Student()
p1.cn = 90
p1.en = 101

原文链接:https://www.f2er.com/note/421955.html

猜你在找的程序笔记相关文章