python __slots__使用详解
1.动态添加属性
class Lang(object): def __init__(self,name,score): self.name=name self.score=score def langinfo(self): print '%s:%s'%(self.name,self.score) lang1=Lang('Python','8.5') lang1.rank=4 print lang1.rank
运行结果:
2.动态添加方法
from types import MethodType class Lang(object): def __init__(self,name,score): self.name=name self.score=score def langinfo(self): print '%s:%s'%(self.name,self.score) lang1=Lang('Python','8.5') def getrank(self): return 4 lang1.getrank=MethodType(getrank,lang1,Lang) print lang1.getrank()
运行结果:
这种方法只是给实例lang1,动态添加了方法
from types import MethodType class Lang(object): def __init__(self,name,score): self.name=name self.score=score def langinfo(self): print '%s:%s'%(self.name,self.score) lang1=Lang('Python','8.5') lang2=Lang('C','9') def getrank(self): return 4 lang1.getrank=MethodType(getrank,lang1,Lang) print lang2.getrank()
运行结果:
给类添加方法:
from types import MethodType class Lang(object): def __init__(self,name,score): self.name=name self.score=score def langinfo(self): print '%s:%s'%(self.name,self.score) lang1=Lang('Python','8.5') lang2=Lang('C','9') def getrank(self): return 4 Lang.getrank=MethodType(getrank,None,Lang) print lang2.getrank()
运行结果:
3.限制Class属性 __slots__
#__slots__使用 from types import MethodType class Lang(object): __slots__=('name','score','rank') def __init__(self,name,score): self.name=name self.score=score def langinfo(self): print '%s:%s'%(self.name,self.score) lang1=Lang('Python','8.5') lang1.rank=4 lang1.desc='Simple' print lang1.rank
运行结果: