`
lingyibin
  • 浏览: 190865 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

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

阅读更多

 

 

#encoding=UTF-8
'''
Created on 2011-5-26

@author: Administrator
'''

#静态变量
class A:
    count=0
    def __init__(self):
        self.__class__.count+=1 #把它当全局变量来用

print A.count
a=A()
print a.count
b=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 a
print x #结果被__str__重写了

print repr(x) #repr函数用来取得对象的规范字符串表示。重写__repr__
print eval("A()")
    
'''
0
1
2
<__main__.A instance at 0x01AEE828>
OK,I am in the class
A()
<__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  #true
print 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 #0
isDogAlive(d)  #Dead
    
d.alive = 3
isDogAlive(d) #Alive

##########################
#__len__
class D:
    def __len__(self):
        return 100

d = D()
print len(d) #100
    
    
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics