【python】动态绑定属性和方法MethodType及限制动态绑定__slots__

一。动态绑定方法

1.运行时给类动态绑定方法
from types import MethodType
class Person(object):
    pass

def set_age(self,age):
    self.age = age

def main():
    p1 = Person()
    p2 = Person()
    Person.set_age = MethodType(set_age,Person)  #动态绑定类
    p1.set_age(11)
    p2.set_age(22)
    print(p1.age)
    print(p2.age)

if __name__ == '__main__':
    main()
#执行后结果,分析:该方法绑定的是Person类,所有实例指向该方法,共享该方法
#<<<22
#<<<22

2.针对上述问题,可以绑定实例
from types import MethodType
class Person(object):
    pass

def set_age(self,age):
    self.age = age

def main():
    p1 = Person()
    p2 = Person()
    p1.set_age = MethodType(set_age,p1)
    p2.set_age = MethodType(set_age,p2)
    p1.set_age(11)
    p2.set_age(22)
    print(p1.age)
    print(p2.age)

if __name__ == '__main__':
    main()
#执行后结果,分析:该方法绑定的是各个实例,所有指向不同,各个不干涉
#<<<11
#<<<22

二。限制动态绑定属性和方法

1.限制动态绑定方法
from types import MethodType
class Person(object):
    __slots__ = ("name","age") # it's tuple
    pass                       #限制绑定属性或方法只能是name和age      

def set_age(self,age):
    self.age = age

def main():
    p1 = Person()
    p1.set_age = MethodType(set_age,p1)
    p1.set_age(11)
    print(p1.age)

if __name__ == '__main__':
    main()
#执行报错: 'Person' object has no attribute 'set_age'
#只有加上__slots__ = ("name","age","set_age")才能执行成功,动态绑定成功
2.限制绑定属性
from types import MethodType
class Person(object):
    __slots__ = ("name","age","set_age") # it's tuple
    pass

def set_age(self,age):
    self.age = age

def main():
    p1 = Person()
    p1.set_age = MethodType(set_age,p1)
    p1.set_age(11)
    print(p1.age)
    p1.score=10     #执行时新增属性score,就会报错了
    print(p1.score) #AttributeError: 'Person' object has no attribute 'score'

if __name__ == '__main__':
    main()

你可能感兴趣的:(python)