Python面向对象高级编程-_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
>>> 

但是给一个实例绑定的方法,对另一个实例是不起作用的:

>>> s1 = Student()
>>> s1.name = 'Jack'
>>> s1.name
'Jack'
>>> s1.set_age(24)

Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    s1.set_age(24)
AttributeError: 'Student' object has no attribute 'set_age'
>>> 

为了给所有实例都绑定方法,可以给class绑定方法:

>>> Student.set_age = set_age
>>> s1.set_age(24)
>>> s1.age
24
>>> 

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

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

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

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

    
>>> s = Student()
>>> s.score = 99

Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    s.score = 99
AttributeError: 'Student' object has no attribute 'score'
>>> 

除非在子类中也定义__slot__,这样子类实例允许定义的属性就是自身__slots__加上父类的__slot__

posted @ 2017-11-02 14:03  起床oO  阅读(221)  评论(0编辑  收藏  举报