使用__slots__:
正常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以
给该实例绑定任何属性和方法,这就是动态语言的灵活性,先定义class:
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print '%s: %s' % (self.name, self.score -2)
然后,尝试给实例绑定一个属性:
from mycompany.web.Student import *
s=Student('a','b')
print s.name
s.name='Michael'
print s.name
C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/a2.py
a
Michael
还可以尝试给实例绑定一个方法:
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print '%s: %s' % (self.name, self.score -2)
def set_age(self, age): # 定义一个函数作为实例方法
self.age = age
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print '%s: %s' % (self.name, self.score -2)
def set_age(self, age):
self.age = age
return self.age
from mycompany.web.Student import *
s=Student('a','b')
print s.name
s.name='Michael'
print s.name
print s.set_age(77)
通常情况下,上面的set_score方法可以直接定义在class中,但动态绑定允许我们在程序
运行的过程中动态给class加上功能,这在静态语言中很难实现。
使用__slots__
但是,如果我们想要限制class的属性怎么办?比如,只允许对Student实例添加name和age属性:
为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量,
来限制该class能添加的属性:
class Student(object):
def __init__(self, name,age, score):
self.name = name
self.age = age
self.score = score
def print_score(self):
print '%s: %s' % (self.name, self.score -2,self.score)
-----------------------------------------------------------------------------
class Student(object):
def __init__(self, name,age, score):
self.name = name
self.age = age
self.score = score
def print_score(self):
print '%s: %s' % (self.name, self.score -2,self.score)
from mycompany.web.Student import *
s=Student('a',12,23)
print s.name
s.name='Michael'
print s.name
print '---------------------------'
print s.age
s.age=34
print s.age
print '---------------------------'
print s.score
s.score=45
print s.score
C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/a2.py
a
Michael
---------------------------
12
34
---------------------------
23
45
class Student(object):
__slots__ = ('name','age','score')
def __init__(self, name,age, score):
self.name = name
self.age = age
self.score = score
def print_score(self):
print '%s: %s' % (self.name, self.score -2,self.score)
from mycompany.web.Student import *
s=Student('a',12,23)
print s.name
C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/a2.py
a
此时可以: