您的位置:首页 > 其它

运算符重载

2015-11-14 22:42 288 查看
#-*-coding:utf-8-*-
'''
Created on 2015年11月14日

@author: Zroad
'''

"""
一、运算符重载的概念:
1、类方法中拦截内置的操作
2、当类的实例处置内置操作,Python自动调用该方法
"""

"""
二、内置操作符与类方法对应关系:
__init__   -> 构造函数,X = Class(args)
__del__    -> 析构函数,X对象被回收
__add__    -> 运算符+,无__iadd__,X+Y,X+=Y
__or__     -> 运算符|,X|Y,X |= Y
__str__    -> 转换 , str(X)
__repr__   -> 打印  , print(X),repr(X)
__call__   -> 函数调用 ,X(*args,**kargs)
__getattr__ -> 点号运算, X.undefined
__setattr__ -> 属性赋值语句,X.any = value
__delattr__ -> 属性删除 , del X.any
__getattribute__ ->属性获取, X.any
__getitem__ -> 索引运算 , X[key],X[i:j]
__setitem__ -> 索引赋值,X[key] = value X[i:j] = sequence
__delitem__ -> 索引和分片删除  del X[key], del X[i:j]
__len__     -> 长度, len(X)
__bool__(__nonzero__ py2.6中),  ->bool(X)
__lt__,__gl__  ->比较运算符, X < Y, X > Y
__le__,__ge__, ->比较运算符,X <= Y,X >= Y
__eq__.__ne__, ->比较运算符, X == Y,X != Y
__radd__,   -> 右侧加法, Other + X
__iadd__,   -> 加强加法,X += Y
__contains__,  ->成员关系测试, item in X
__index__,  -> 整数值,hex(X),bin(X),oct(X)
__new__,    -> 在__init__之前创建对象
"""

"""
三、运算符重载实例,索引、分片、自定义迭代器
"""
#1、重载索引
class Indexer(object):

def __getitem__(self,index):
return index ** 2

X = Indexer()
print ("X[5]=",X[5])  #X[5]= 25

#2、属性引用
class Empty(object):

def __getattr__(self,attrname):   #访问未定义属性时执行该方法
if attrname == "age":
return 40
else:
raise AttributeError,attrname

e = Empty()
print "e.age = ",e.age
#print "e.name = ",e.name

class AccessControl(object):

def __setattr__(self,attrname,value):
if attrname == "age":
self.__dict__[attrname] == value
else:
raise AttributeError,attrname + "not allowed!"

a = AccessControl()
a.age = 40
a.name = "zr"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  运算符重载