首页 > 编程语言 > 详细

python __slots__

时间:2020-02-10 20:47:28      阅读:50      评论:0      收藏:0      [点我收藏+]

Python是动态语言,任何实例在运行期都可以动态地添加属性。

如果要限制添加的属性,例如,Student类只允许添加 name、gender和score 这3个属性,就可以利用Python的一个特殊的__slots__来实现。

顾名思义,__slots__是指一个类允许的属性列表:

 

技术分享图片
class Student(object):
    __slots__ = (name, gender, score)
    def __init__(self, name, gender, score):
        self.name = name
        self.gender = gender
        self.score = score
s=Student(Peter,male,99)
s.age=28
print(s.age)
View Code

 

如果注销__slots__ = (‘name‘, ‘gender‘, ‘score‘)

程序正常运行,为实例化对象添加age属性

 

如果添加__slots__属性,程序报错:

AttributeError: ‘Student‘ object has no attribute ‘age‘

不允许添加slots列表内以外的属性

 

__slots__的目的是限制当前类所能拥有的属性,如果不需要添加任意动态的属性,使用__slots__也能节省内存。

python __slots__

原文:https://www.cnblogs.com/pfeiliu/p/12292419.html

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