使用__slots__:
正常情况下,当我们定义了一个class,创建了夜歌class的实例后,我们可以给该梳理绑定任何属性和方法,
给实例绑定一个属性:
class Student(object):
pass
s=Student()
s.name='aaa'
print s.name
给class 绑定方法:
使用__slots__
class Student(object):
pass
s=Student()
s.name='aaaa'
s.score='bbbb'
s.age='ccc'
print s.name
print s.score
print s.age
C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a21.py
aaaa
bbbb
ccc
为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class能添加的属性:
# !/usr/bin/env python
# -*- coding: utf-8 -*-
class Student(object):
__slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
s=Student()
s.name='aaaa'
s.score='bbbb'
s.age='ccc'
print s.name
print s.score
print s.age
C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a21.py
Traceback (most recent call last):
File "C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a21.py", line 7, in <module>
s.score='bbbb'
AttributeError: 'Student' object has no attribute 'score'