python学习:限制实例的属性

来源:互联网 发布:淘宝成功的原因 编辑:程序博客网 时间:2024/05/29 16:22

若要限制某一实例只具有某几个属性,该怎么办呢?

在定义class的时候,定义__slots__变量,来限制该class实例能添加的属性:

举例:

>>> class Student(object):__slots__ = ('name','age')>>> s = Student()>>> s.name='xiaoh'>>> s.age=25>>> s.mobie='13955698985'  #因未绑定该属性,所以会报 AttributeErrorTraceback (most recent call last):  File "<pyshell#356>", line 1, in <module>    s.mobie='13955698985'AttributeError: 'Student' object has no attribute 'mobie'

说明:使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:除非在子类中也定义__slots__

,子类中定义后,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__

阅读全文
0 0
原创粉丝点击