class Student(object): say="this is a student class" def __init__(self,name,age):#构造器 self.name = name self.age = age @classmethod#类方法 def showClassMethod(cls): print "call classmethod" print cls.say @staticmethod#静态方法,属于类 def showStaticMethod(): print "call static method" print Student.say @property#包装器定义属性 def sex(self): print "call property" return self._sex @sex.setter#包装器设置sex def sex(self,value): print "call setter" self._sex = value def getSex(self):#外部获取sex属性 return self._sex def showAll(self):#类对象调用 print "call instance method" print self.age,self.name,self.sex,self.getSex() def __del__(self):#析构函数 print "call destructor" def __str__(self):#获取类对象的字符串描述 return "student object:(name:%s)(age:%d)" % (self.name,self.age) def __repr__(self):#调试用 例如在控制台调用:s return self.__str__() def __getattr__(self, item):#获取非定义的属性 if item == "score": return lambda :99 elif item == "dog": return "xiaohuang" else: raise "attr error" def __call__(self, *args, **kwargs): #调用自己 print "__call__ self:" for i in range(len(args)):#打印元组 print args[i] for i in kwargs:#打印键值对 print i,kwargs[i] print "call:my name is zhengjinwei" Student.showClassMethod() #调用类方法 s = Student("zhengjinwei",24) s.sex = "male" #调用sex的包装器,此处要注意的是Student类必须继承自object才能使用包装器 s.grade = "1" #动态创建属性 print s.grade print s #调用 __str__ print s.score() #调用__getattr__ print s.dog #调用__getattr__ if callable(s): s(1,2,3,name="zjw",age=24) #调用 __call__ s.showClassMethod() s.showStaticMethod() s.showAll()
结果:
<span style="font-size:18px;">call classmethod this is a student class call setter 1 student object:(name:zhengjinwei)(age:24) 99 xiaohuang __call__ self: 1 2 3 age 24 name zjw call:my name is zhengjinwei call classmethod this is a student class call static method this is a student class call instance method 24 zhengjinwei call property male male call destructor </span>