限制属性绑定(__slots__)
发布日期:2021-05-10 03:51:49 浏览次数:18 分类:精选文章

本文共 2628 字,大约阅读时间需要 8 分钟。

���Python������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Python���������������������������������������������������������������������������**__slots__**���������

���������__slots__���

__slots__������������������������������������������������������������������������������������__slots__������������������������������������������������������������������������������������������������������������������������������

������������

������������������������Student���������������������������name���age���������

class Student(object):
__slots__ = ('name', 'age') # ������������������������������������tuple���
student = Student()
student.name = 'Michael' # ������������'name'
student.age = 25 # ������������'age'
try:
student.score = 99 # ������������������__slots__������������
except AttributeError:
print("������'score'������������")

������������������������student.score = 99���������AttributeError���������score������__slots__������

__slots__������������

���������������������������__slots__������������������������������������������������������������������

class Student(object):
__slots__ = ('name', 'age')
class GraduateStudent(Student):
pass
grad_student = GraduateStudent()
try:
grad_student(score=9999) # ������������������
except AttributeError:
print("������'score'������������")

grad_student������������name���age���������������Student������������������������������������������������������������������������������__slots__������������������������������������������������������

������������__slots__

���������������������������������������������������������������__slots__���

class Student(object):
__slots__ = ('name', 'age')
class GraduateStudent(Student):
__slots__ = ('score')
grad_student = GraduateStudent()
grad_student.name = 'Michael' # ������������������'name'
grad_student.age = 25 # ������������������'age'
grad_student.score = 99 # ������������������'score'
try:
grad_student.city = 'DaLian' # ���������������������������������������
except AttributeError:
print("������'city'������������")

���������������������������������������������������������������������������

������

__slots__���Python���������������������������������������������������������������������������������������������������__slots__���������������������������������������������������������������������������������������������������������������������������������������

上一篇:参数检查(@property)
下一篇:实例属性和类属性

发表评论

最新留言

关注你微信了!
[***.104.42.241]2025年04月04日 21时40分54秒