Python之__slots__

一、前言

        最近学习廖雪峰官网的python,学习后,简单总结下

        当我们定义一个class,创建一个class的实例后,就可以给实例绑定方法和属性。这是动态语言的灵活性。

class Student(object):
        pass
#这是给实例绑定属性
>>s=Student()
>>s.name="Balllyh"
>>print(s.name)
Ballyh
#这是给实例绑定方法
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)#调用实例方法
s.age#测试结果=25

s2=Student()#创建新实例s2
s2.set_age(26)#尝试调用新方法--》报错,这个实例未绑定set_age方法。

 给class绑定方法后,所有实例均可调用

def set_score(self,score):
        self.score=score

>>Student.set_score=set_score
>>s=Student()
>>s2=Student()
>>s.set_score(199)
199
>>s2.set_score(89)
89

 二、使用__slots__

    (1)使用__slots__可以限制实例的属性,举例,只给Student类添加name和age属性。

     

    由于__slots__未绑定score属性,所以直接调用会报错

(2)__slots__绑定的属性只对当前类有用,对继承子类无作用。

        只有继承子类用__slots__自己绑定属性后,它允许的属性=自身__slots__绑定属性+父类绑定的属性

     

    

原文地址:https://www.cnblogs.com/balllyh/p/13347133.html