动态绑定方法与 __slots__

Python属于动态语言,可以在类定义之外为实例新增属性与方法。

class Master(object):
    def printstudent(self):
        print('100 fen')
s=Master()
def setage(self,age):
    self.age=age
from types import MethodType
s.setage=MethodType(setage,s)
s.setage(25)
print(s.age)

步骤为新建实例,然后定义需要新增的方法,引入MethodType函数,MethodType函数的原型为method(function, instance)  

|  __func__
 |      the function (or other callable) implementing a method
 |  
 |  __self__
 |      the instance to which a method is bound

MethodType把函数绑定到实例中,然后在实例s中新建一个link指向该函数。该函数只对s实例起作用,若用同一个类实例化s1,则s1没有该函数。

为了能给所有实例都使用该函数,可以给类绑定该函数。

s=Master()
def setage(self,age):
self.age=age
Master.setage=setage
s.setage(25)
print(s.age)

__slots__的作用在于限制类的实例能添加的属性(包括在类定义中的属性),只要__slots__没有包含的属性,实例中禁止动态添加。  

class Student(object):
    __slots__=('__name','__score')
    def __init__(self, name, score):
        self.__name = name
        self.__score = score
s=Student('kimi',90)
s.x=9999#报错,提示Student没有x属性
print(s.x)

__slots__作用仅限于类自身,不影响子类,但是如果子类也定义了__slots__,那么子类的范围就包括了子类自身限制与基类限制的并集