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
    
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值