首页 > 编程语言 > 详细

python之__slots__用法

时间:2020-08-23 18:18:22      阅读:69      评论:0      收藏:0      [点我收藏+]

一、背景

python是一个动态语言,可以支持我们在运行时动态的给类、对象添加属性或者方法;但是如果我们想要限制可以添加的属性或方法该怎么办呢?

二、__slots__

python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class能添加的属性:

>>> class Student(object):
...     __slots__ = (‘name‘, ‘age‘) # 用tuple定义允许绑定的属性名称
...

然后尝试添加属性:

>>> s = Student() # 创建新的实例
>>> s.name = ‘Michael‘ # 绑定属性‘name‘
>>> s.age = 25 # 绑定属性‘age‘
>>> s.score = 99 # 绑定属性‘score‘
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: ‘Student‘ object has no attribute ‘score‘

由于‘score‘没有被放到__slots__中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。
使用__slots__要注意,__slots__定义的属性仅对当前类起作用,对继承的子类是不起作用的:

>>> class GraduateStudent(Student):
...     pass
...
>>> g = GraduateStudent()
>>> g.score = 9999

除非在子类中也定义__slots__,这样,子类允许定义的属性就是自身的__slots__加上父类的__slots__。

python之__slots__用法

原文:https://www.cnblogs.com/lit10050528/p/13549762.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!