学习廖雪峰老师的python教程中的使用__slots__的笔记:
第一部分:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Student(object):
pass
s=Student()
s.name=('Michael')#给实例绑定属性
print(s.name)
##########给实例绑定方法##############
def set_age(self,age):
self.age=age
from types import MethodType
s.set_age=MethodType(set_age,s)#给s绑定set_age方法
s.set_age(25)
s2 = Student()
#s2.set_age(25) #给一个实例绑定的方法对另一个实例是不起作用的,不注释掉程序会卡在这里
print("the age of s is:",s.age)
#print("the age of s2 is:",s2.age)
#############给class绑定方法,所有实例都可用#############
def set_score(self, score):
self.score = score
Student.set_score = set_score
s.set_score(100)
print("the score of s is:",s.score)
s2.set_score(99)
print("the score of s2 is:",s2.score)
第二部分:使用__slots__
Python允许在定义class的时候,定义一个特殊的__slots__
变量,来限制该class实例能添加的属性:
__slots__
定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Student(object):
__slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
s = Student() # 创建新的实例
s.name = 'Michael' # 绑定属性'name'
print("the name of s is",s.name)
s.age = 25 # 绑定属性'age'
print("the age of s is",s.age)
#s.score = 99 # 绑定属性'score',应该是不成功的,因为 __slots__中不包含score属性
#print("the score of s is",s.score)
###################__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:###################
class GraduateStudent(Student):
pass
g=GraduateStudent()
g.score=900
print("the score of s is",g.score)