python学习-slots

来源:互联网 发布:北京学软件测试 编辑:程序博客网 时间:2024/06/10 12:37
#!/usr/bin/env python#-*- coding:utf-8 -*-'slots'__author__ = 'hui.qian''''之前一章给类动态的增加属性,现在给类动态的增加方法'''class Student(object):    passs = Student()s.name = 'hui.qian'print s.name#首先定义一个方法def set_age(self,age):    self.age = agefrom types import MethodTypes.set_age = MethodType(set_age,s,Student)s.set_age(25)print s.age#动态添加成功,如果这个时候我创建一个Student的实例#还能用set_age()方法么#s1 = Student()#print s1.set_age(25)#上面的调用会报错,说明刚才的添加方法只是暂时的#如果想让其他实例也拥有这样的方法,定义如下def set_score(self,score):    self.score = scoreStudent.set_score = MethodType(set_score,None,Student)s2 = Student()s3 = Student()s2.set_score(99)print s2.scores3.set_score(100)print s3.score'''那么再来说说__slots__有什么作用:像上面的给类添加属性的方式,应该是随意添加一个属性但是有人就不希望你随意添加,他就得使用__slots__来标识哪些属性可以添加'''class Student(object):    __slots__ = ('name','age')s = Student()s.name='hui.qian'print s.names.age=25print s.age#上面的赋值都是正确的,但是下面的赋值就会报错#s.score = 55#因为score不在__slots__中'''__slots__仅对当前类有用,对于没有定义__slots__的子类不起作用如果子类定义了__slots__,那么其作用的关键字就是父类和子类的__slots__的合集'''

1 0
原创粉丝点击