python的__slots__使用

使用__slots__
使用原因
python是动态语言,可以动态的对已经定义好的对象进行增加,修改属性操作
作用
在类中定义,采用tuple限制了该类的动态属性定义
实例
#限制Student类只可以增加name,age属性
class Student(object):
    __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
因为score没有在__slots__中定义,所以实例化Student,动态添加score时出现“AttributeError”错误
>>> s = Student() # 创建新的实例
>>> s.name = 'syy' # 绑定属性'name'
>>> s.age = 30 # 绑定属性'age'
>>> s.score = 99 # 绑定属性'score'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'
==注意:==如子类继承了有__slots__定义的父类,且没有在子类中实现__slots__,那么父类定义的__slots__不会影响子类;如果子类实现了__slots__那么子类实例化后,添加属性的限制范围为,父类和子类__slots__定义的集合
#子类没有实现__slots__
>>> class A(Student):
...     pass
...
>>> g = A()
>>> g.name = 'fff'
>>> g.name
'fff'
>>> g.score = 98
>>> g.score
98
#子类实现__slots__,且不新增
>>> class C(Student):
...     __slots__ = ()
...
>>> s = C()
>>> s.name = 'sss'
>>> s.name
'sss'
>>> s.score = 89
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'score'

#子类实现__slots__,且新增
>>> class D(Student):
...     __slots__ = ('score')
...
>>> d = D()
>>> d.score = 32
>>> d.score
32
>>> d.sxe
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'D' object has no attribute 'sxe'
>>> d.sxe = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'D' object has no attribute 'sxe'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值