python 面向对象编程的__slots__

同一个类下,不同实例定义的属性或者方法,其他实例如果没有定义是不能使用的

#定义一个类
class Student(object):
    pass


#给类绑定一个实例
s=Student()

#给实例绑定一个属性
s.name='Micheal'
s.name   #'Micheal'

s1=Student()
s1.name    #报错AttributeError: 'Student' object has no attribute 'name' 

我们如果想要给所有实例都绑定属性或者方法,只需给类绑定属性或者方法就可以了,这样所有的实例都可以调用

但是我们想要限制实例的属性,比如说实例只能添加name和age属性

在定义类时,使用__slots__变量,来限制类实例能添加的属性

__slots__变量的使用方法

class Student(object):
    __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称



s = Student() # 创建新的实例
s.name = 'Michael' # 绑定属性'name'
s.age = 25 # 绑定属性'age'
s.score = 99 # 绑定属性'score'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'

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

 class GraduateStudent(Student):
     pass

 g = GraduateStudent()
 g.score = 9999  #这样是没有问题的

 

posted on 2020-07-15 14:31  小小喽啰  阅读(113)  评论(0编辑  收藏  举报