第9章-Python风格的对象格式表示法>>>print"Hello%(name)s!"%{'name':'James'}你好詹姆斯!>>>print"Iamyears%(age)iyearsold"%{'age':18}我今年18岁#format:>>>print"Hello{name}!".format(name="詹姆斯”)你好,詹姆斯!__slots__方法在Python中有很多内置属性,其中__slots__属性很少用到,基本不会被当成必选项。但是如果你对内存使用有很高的要求,__slots__会帮到你很多。__slots__的目的是什么?答案是:优化内存使用。限制实例属性的自由添加只是一个副作用。那么__slots__属性到底有多神奇呢?这从__dict__属性开始。__dict__属性的作用是记录实例属性:__dict__属性用于记录实例中的属性信息。如果修改了实例中的属性信息,或者增加了新的属性,__dict__会记录下来。classPerson(object):def__init__(self,name,age):self.name=nameself.age=ageperson=Person("tony",20)#实例化Personclassprint(person.__dict__)#记录实例Allattributes{'name':'tony','age':20}person.age='jacky'person.gender='male'print(person.__dict__)#{'name':'tony','age':'jacky','gender':'male'}那么__slots__与__dict__有什么关系呢?简单理解:__slots__的取值就是删除__dict__属性,从而优化类实例的内存需求。而这样做的副作用就是:由于缺少了__dict__,类实例就没有办法随意添加属性了!classPerson(object):__slots__=("name","age")def__init__(self,name,age):self.name=nameself.age=ageperson=Person("tony",20)#ForPerson类Instantiateprint("__dict__"indir(person))#False,没有__dict__属性person.age='jacky'person.gender='male'#AttributeError:'Person'objecthasnoattribute'gender'#这是__slots__的副作用,不能随意添加实例属性元素个数要多(为了减少哈希冲突的概率),这样会浪费一定的空间。在new-style类中使用__slots__是为了告诉Python虚拟机这种类型的对象只会使用这些属性,所以虚拟机要预留足够的空间。如果声明了__slots__,该对象将不再具有__dict__属性。能节省多少取决于类本身有多少个属性,属性的类型,同时存在多少个类的实例。你可以查看这个链接,我们可以自己测试结果:#UseprofileforperformanceanalysisimportprofileclassA(object):def__init__(self,x,y):self.x=x自我。y=ydefprofile_result():f=[A(1,2)foriinrange(100000)]if__name__=="__main__":profile.run("profile_result()")返回结果:100006次函数调用在0.297秒内排序:标准名称ncallstottimepercallcumtimepercallfilename:lineno(function)10.0000.0000.2970.297:0(exec)10.000000.000000(setprofile)10.0160.0160.2970.297
