Python2.7类的绑定
利用 MethodType()函数来绑定
绑定到对象
对于语句:stu1.SetName = types.MethodType(SetName, stu1, Student)来说
MethodType是把外部函数SetName()绑定到对象stu1的身上成为它的一个方法
绑定只可以通过本对象来可以调用这个方法
绑定到类
语句 | Student.SetAge = types.MethodType(SetAge, None, Student) | Student.SetScore = types.MethodType(SetScore, Student) |
不同点 | 不同对象调用的外部函数处于不同的空间,所以不同对象之间互不影响 | 这种情况下,不同对象调用的外部函数处于同一空间,所以后面对象调用外部函数会影响前面的结果,即对象之间是相互影响的 |
相同点 | MethodType是把外部函数SetName()绑定到Student类的身上成为它的一个方法绑定一次就可以所有的对象都可以调用这个方法 |
样例代码
# -*- coding: utf-8 -*-
import types
#定义类
class Student:
def __init__(self):
pass
def PrintName(self):
print 'name=',self.name
def PrintAge(self):
print 'age=',self.age
def PrintScore(self):
print 'score=', self.score
#外部函数
def SetName(self, name1):
self.name = name1
def SetAge(self, age1):
self.age = age1
def SetScore(self, score1):
self.score = score1
stu1 = Student()
stu2 = Student()
stu3 = Student()
#1. 将外部方法绑定到对象实例上
stu1.SetName = types.MethodType(SetName, stu1, Student)
stu2.SetName = types.MethodType(SetName, stu2, Student)
stu3.SetName = types.MethodType(SetName, stu3, Student)
stu1.SetName('hello')
stu2.SetName('world')
stu3.SetName('python')
stu1.PrintName()
stu2.PrintName()
stu3.PrintName()
#此时只能通过特定的对象调用绑定的外部函数
#2. 将外部方法绑定到类上(有None参数)
Student.SetAge = types.MethodType(SetAge, None, Student)
stu4 = Student()
stu5 = Student()
stu6 = Student()
stu4.SetAge(10)
stu5.SetAge(20)
stu6.SetAge(30)
stu4.PrintAge()
stu5.PrintAge()
stu6.PrintAge()
#这种情况下,不同对象调用的外部函数处于不同的空间,所以不同对象之间互不影响
#3. 将外部方法绑定到类上(没有None参数)
Student.SetScore = types.MethodType(SetScore, Student)
stu7 = Student()
stu8 = Student()
stu9 = Student()
stu7.SetScore(70.5)
stu8.SetScore(80.5)
stu9.SetScore(90.5)
stu7.PrintScore()
stu8.PrintScore()
stu9.PrintScore()
#这种情况下,不同对象调用的外部函数处于同一空间,所以后面对象调用外部函数会影响前面的结果,即对象之间是相互影响的
使用__slots__来限制绑定
class Student(object):
__slots__ = __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
stu1=Student()
stu1.name="Tom"
print stu1.name
stu1.age=18
print stu1.age
stu1.score=90
print stu1.score
输出
Tom
18
AttributeError: 'Student' object has no attribute 'score'
综上所述:
使用__slots__是用tuple定义允许绑定的属性名称