运算符重载
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"
相关文章推荐
- 详解C++编程中的单目运算符重载与双目运算符重载
- c++ *运算符重载
- C++重载运算符的规则详解
- c++运算符重载基础知识详解
- C++运算符重载的方法详细解析
- 简介C++编程中的运算符重载
- C++运算符重载规则详解
- operator int-C++
- 运算符重载:友元(friend)函数问题
- C++运算符重载Sample
- 重载及运算符重载需要注意的地方
- c++运算符重载
- c++运算符重载
- 运算符重载时到底发生了什么?【DEBUG】
- 浅谈C++中用友元函数的方法实现复合运算符(+=等)的重载方法
- 错误集锦1
- C++ 之 运算符重载
- python学习笔记——类
- C++ How to program 9E<10.9 hugeInt Class 函数运算符重载>
- C++ <使用函数运算符重载执行类对象加法>