python: __slots__

当我们创建了一个类之后,我们可以给类绑定上任意属性和方法:
绑定只针对当前实例的对象,对其他实例对象无效,如s和s2,同样是实例化Student(),s绑定了name,s2并没有生效。

>>> class Student(object):
...     pass
...
>>> s = Student()
>>> s.name = '张三'
>>> s.name
'张三'
>>> s2 = Student()
>>> s2.name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'name'
>>>

如果类本身有这个属性,实例化出来的对象又绑定了同样的属性名,那么通过实例对象去查看属性名,返回的是实例化对象绑定的属性值。比如,s实例绑定了name,并赋值,那么s.name 就是‘Ace’,而不是Student()的‘Luffy’,但Student()的name还是‘Luffy’,再次被实例为s2时,s2调用name还是显示‘Luffy’。

所以,实例对象绑定的属性名最好不要和类属性名一样,避免当实例对象绑定属性名一致时覆盖类的属性值,避免删掉实例对象后,使用的属性值又变回类属性值。
>>> class Student(object):
...     self.name = 'Luffy'
...
>>> s = Student()
>>> s.name
'Luffy'
>>> s.name = 'Ace'
>>> s.name
'Ace'
>>> Student().name
'Luffy'
>>> s2 = Student()
>>> s2.name
'Luffy'
使用slots

如果控制实例绑定指定的属性,可以加上使用slots特殊变量:
如果实例对象绑定的不是对象的属性,会报AttributeError错误

>>> class Student(object):
...     __slots__ = ('name', 'age')
...
>>> s = Student()
>>> s.name = 'Luffy'
>>> s.name
'Luffy'
>>> s.age = 12
>>> s.age
12
>>> s.gender = '1'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'gender'

但是父类的slots对子类是无效的:

>>> class LittleStudent(Student):
...     pass
...
>>> ls = LittleStudent()
>>> ls.gender = '1'
>>> ls.gender
'1'
>>>

如果想限制,子类需通过slots加上除父类内限制的属性外,自己还想限制的属性,此时子类再绑定gender属性就会报AttributeError错误

>>> class LittleStudent(Student):
...     __slots__ = ('address')
...
>>> ls = LittleStudent()
>>> ls.address = 'beijing'
>>> ls.address
'beijing'
>>> ls.name = 'aaa'
>>> ls.name
'aaa'
>>> ls.gender = '1'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'LittleStudent' object has no attribute 'gender'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值