#######################################################################################
# Author : CHR_崔贺然
# Time : 20200412
# TODO : description描述符,需求做一个成绩管理系统,在property、staticmethod、classmethod中都有使用
# *
# !
# ?
#######################################################################################
# # 这种方法很笨,需要对入参做类型检查
# class Student:
# def __init__(self, name, math, chinese, english):
# self.name = name
# self.math = math
# self.chinese = chinese
# self.english = english
# # 推荐每个类都要带上__repr__
# def __repr__(self):
# return f"姓名:{self.name},数学:{self.math},语文:{self.chinese},英语:{self.english}"
# s1 = Student("崔贺然", 100, 100, 100)
# print(s1)
# 改进版
class Score:
def __init__(self, default=0):
self._score = default
def __set__(self, instance, value):
if not isinstance(value, int):
raise ValueError("score must be integer")
if not 0 <= value <= 100:
raise ValueError("value must be in 0-100")
self._score = value
def __get__(self, instance, owner):
return self._score
def __del__(self):
del self._score
class Student:
math = Score(0)
chinese = Score(0)
english = Score(0)
def __init__(self, name, math, chinese, english):
self.name = name
self.math = math
self.chinese = chinese
self.english = english
def __repr__(self):
return f"姓名:{self.name},数学:{self.math},语文:{self.chinese},英语:{self.english}"
s1 = Student("崔贺然", 100, 100, 100)
print(s1)
Python的描述符
最新推荐文章于 2025-01-16 22:21:19 发布
1243

被折叠的 条评论
为什么被折叠?



