Python 5.1 使用 __slots__

使用__slots__


正常情况下, 当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这是动态语言的灵活性。先定义class:

class Student(object):
    pass

然后尝试给实例绑定一个属性:
>>>s =Student()

>>>s.name ='Michael'

>>>print(s.name)

Michael

还可以尝试给实例绑定一个方法:
>>>def set_age(self,age):
    self.age =age


>>>from types import MethodType

>>>s.set_age =MethodType(set_age,s)

>>>s.set_age(25)

>>>s.age

25

但是,给一个实例绑定的方法,对其他实例是不起作用的:
>>>s2 =Student()

>>>s2.set_age(25)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  AttributeError: 'Student' object has no attribute 'set_age'

为了给所有实例绑定方法,可以给class绑定方法:
>>>def set_score(self,score):

    self.score =score

>>>Student.set_score =MethodType(set_score,Student)

给class绑定方法后,所有实例均可以用:
>>>s.set_score(100)

>>>s.score

100

>>>s2.set_score(99)

>>>s.score

99

通常情况下,上面的set_score方法可以直接定义到class中,但是动态绑定允许我们在程序的运行过程中动态给class加上功能,这在静态语言中是很难实现的。


使用__slots__


但是如果想要限制实例的属性,该怎么办呢?比如,只允许对Student增加name和age属性。

为了达到限制的目的,Python允许在定义class时,定义一个特殊的__slots__变量,来限制该class实例能添加的属性。

class Student(object):
    __slots__ =('name','age')

然后我们试试:

>>>s =Studnet()

>>>s.name ='Bob'

>>>s.age =25

>>>s.score

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'

由于'score'没有被放到'__slots__'中,所以不能绑定score属性,试图绑定score讲得到AttributeError的错误。

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

>>>class GraduateStudent(Student):
      pass

>>>g =GraduateStudent()

>>>g.score =999

除非在子类中也定义了__slots__,这样,子类允许定义的属性就是自身的__slots__加上父类的__slots__的并集。


你可能感兴趣的:(python,__slots__)