Python3基础-__slots__

1、what

__slots__ :是一个类变量,变量值可以是列表,元祖,或者可迭代对象,也可以是一个字符串(意味着所有实例只有一个数据属性)

2、why 

字典会占用大量的内存,如果有一个属性很少的类;但是又很多实例。为了节省内存可以使用__slots__ 取代实例的__dict__

3、

为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性

class People:
    __slots__ = 'name'  #允许绑定的属性名称

p1 = People()
p1.name = 'susu' #绑定属性name
print(p1.name)  #输出 susu
print(p1.__slots__)
print(People.__slots__)
#p1.age = 28  
#由于'age'没有被放到__slots__中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误
#AttributeError: 'People' object has no attribute 'age'
#print(p1.age) #print(p1.__dict__) #会报错AttributeError: 'People' object has no attribute '__dict__' """ 执行结果如下 susu name name """
class People:
    __slots__ = ('name', 'age') ## 用tuple定义允许绑定的属性名称

p1 = People() #创建实例
p1.name = 'susu'  #绑定属性name
print(p1.name)  #输出 susu
print(p1.__slots__)
print(People.__slots__)
p1.age = 28  #绑定属性age
print(p1.age)

"""
执行结果如下
susu
('name', 'age')
('name', 'age')
28
"""

注意:使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的

posted @ 2019-11-21 15:32  槑槑DE  阅读(299)  评论(0编辑  收藏  举报