面向对象高阶-09__slots__

时间:2019-09-21 14:35:37   收藏:0   阅读:83

什么是slots

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

使用点来访问属性本质就是在访问类或者对象的__dict__属性字典(类的字典是共享的,而每个实例的是独立的)

为什么用slots

class Foo:
    __slots__='x'


f1=Foo()
f1.x=1
f1.y=2#报错
print(f1.__slots__) #f1不再有__dict__

class Bar:
    __slots__=['x','y']
    
n=Bar()
n.x,n.y=1,2
n.z=3#报错

刨根问底

class Foo:
    __slots__=['name','age']

f1=Foo()
f1.name='alex'
f1.age=18
print(f1.__slots__)

输出结果:
[‘name‘, ‘age‘]

f2=Foo()
f2.name='egon'
f2.age=19
print(f2.__slots__)

[‘name‘, ‘age‘]

print(Foo.__dict__)

输出结果:
{‘__module__‘: ‘__main__‘, ‘__slots__‘: [‘name‘, ‘age‘], ‘age‘: <member ‘age‘ of ‘Foo‘ objects>, ‘name‘: <member ‘name‘ of ‘Foo‘ objects>, ‘__doc__‘: None}

原文:https://www.cnblogs.com/suren-apan/p/11561906.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!