在创建一个class时,我们可以直接在创建时给类(class)添加方法,例如:
>>> class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
>>> s1 = Student('Bob', 23, 95)
>>> s1.name
'Bob'
>>> s1.age
23
>>> s1.score
95
与此同时,也可在class创建之后,再给类及实例绑定方法,例如:
1. 给实例绑定方法
>>> class Student(object):
pass
>>> s1 = Student()
>>> s2 = Student()
>>> from types import MethodType
>>> def set_age(self, age):
self.age = age
>>> s1.set_age = MethodType(set_age, s1)
>>> s2.set_age = MethodType(set_age, s2)
>>> s1.set_age(20)
>>> s1.age
20
>>> s2.set_age(30)
>>> s2.age
30
利用types模块中的MethodType函数来为实例s1,s2绑定方法。
2. 给类(class)绑定方法
>>> def set_score(self, score):
self.score = score
>>> Student.set_score = set_score
>>> s1.set_score(90)
>>> s1.score
90
>>> s2.set_score(100)
>>> s2.score
100
给类绑定的方法同样适用与s1、s2实例。
__slots__变量
使用__slots__变量可以限制类以及实例的属性,例如:
>>> class Student(object):
__slots__ = ('name', 'age')
>>> s1 = Student()
>>> s1.name = 'a'
>>> s1.age = 24
>>> s1.score = 90
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
s1.score = 90
AttributeError: 'Student' object has no attribute 'score'
使用__slots__变量限制属性为name、age,故给实例添加score属性,将出现AttributeError错误。
若使用__slots__变量仅对当前类实例起作用,对继承的子类不起作用,例如:
>>> class GraduateStudent(Student):
pass
>>> g = GraduateStudent()
>>> g.score = 98
除非存在在父类和子类都定义了__slots__变量,这样子类实例允许定义的属性就是子类的和父类__slots__相加的范围,例如:
>>> class Student(object):
__slots__ = ('name', 'age')
>>> class JuniorStudent(Student):
__slots__ = ('name', 'sex')
>>> j = JuniorStudent()
>>> j.name = 'Tom'
>>> j.age = 20
>>> j.sex = 'male'
>>> j.score = 100
Traceback (most recent call last):
File "<pyshell#71>", line 1, in <module>
j.score = 100
AttributeError: 'JuniorStudent' object has no attribute 'score'