读书人

python学习札记三(类自定义属性 方法

发布时间: 2012-12-19 14:13:15 作者: rapoo

python学习笔记三(类自定义属性 方法)

?

?

#encoding=UTF-8'''Created on 2011-5-26@author: Administrator'''#静态变量class A:    count=0    def __init__(self):        self.__class__.count+=1 #把它当全局变量来用print A.counta=A()print a.countb=A()print b.count# __str__ 和 __repr__ 和  __del__ 和 __eval__class B:    def __repr__(self):        return "A()"    def __str__(self):        return "OK,I am in the class"    x=B()print aprint x #结果被__str__重写了print repr(x) #repr函数用来取得对象的规范字符串表示。重写__repr__print eval("A()")    '''012<__main__.A instance at 0x01AEE828>OK,I am in the classA()<__main__.A instance at 0x01AEEB20>'''    # __cmp__的用法class C:    def __cmp__(self,other):        if other>=0:return -1        elif other<0: return 1        else: return 0        c = C()print c>-2  #trueprint c>2  #false        # __nozero__ 用法 class Dog:    alive = 0    def __nonzero__(self):        if self.alive==0:return 0        else: return 1;def isDogAlive(d):    if d:print "Alive"    else :print"Dead"    d = Dog()print d.alive #0isDogAlive(d)  #Dead    d.alive = 3isDogAlive(d) #Alive###########################__len__class D:    def __len__(self):        return 100d = D()print len(d) #100        

读书人网 >perl python

热点推荐