classclass_name(base_class): class_var defmethods(self, args): do something
#!/usr/bin/python # -*- coding: utf-8 -*- classA: #classic class 没有父类 """this is class A""" pass __slots__=('x','y') # 可访问"槽"内外的属性 deftest(self): # classic class test """this is A.test()""" print"A class" classB(object): #new class 有父类,python3 都是这种,引入了super的概念 """this is class B""" __slots__=('x','y') # 只能访问"槽"里面的属性 pass deftest(self): # new class test """this is B.test()""" print"B class"
#!/usr/bin/env python # -*- coding: utf-8 -*- #copyRight by heibanke
classCar(object): country = u'中国' __slots__=('length','width','height','owner','__dict__') def__init__(self, length, width, height, owner=None): self.owner = owner self.length = length self.width = width self.height = height def__getattr__(self,name): print"__getattr__",name assert name in self.__slots__, "Not have this attribute "+name return self.__dict__.get(name,None) def__setattr__(self,name,value): print"__setattr__",name assert name in self.__slots__, "Not have this attribute "+name if name!='owner': assert value>0, name+" must larger than 0" self.__dict__[name]=value def__delattr__(self,name): print"__delattr__",name assert name in self.__slots__, "Not have this attribute "+name if name=='owner': self.__dict__[name]=None
if __name__ == '__main__': a = Car(1.2,1.4,1.5,u'黑板客') """ print a.owner del a.owner print a.owner a.length=1 print a.country a.country = 'china' print a.country a.name = u"一汽" """