Python运算符重载用法实例分析


Posted in Python onJune 01, 2015

本文实例讲述了Python运算符重载用法。分享给大家供大家参考。具体如下:

在Python语言中提供了类似于C++的运算符重在功能:

一下为Python运算符重在调用的方法如下:

Method         Overloads         Call for
__init__        构造函数         X=Class()
__del__         析构函数         对象销毁
__add__         +                 X+Y,X+=Y
__or__         |                 X|Y,X|=Y
__repr__        打印转换         print X,repr(X)
__str__         打印转换         print X,str(X)
__call__        调用函数         X()
__getattr_    限制             X.undefine
__setattr__     取值             X.any=value
__getitem__     索引             X[key],
__len__         长度             len(X)
__cmp__         比较             X==Y,X<Y
__lt__         小于             X<Y
__eq__         等于             X=Y
__radd__        Right-Side +         +X
__iadd__        +=                 X+=Y
__iter__        迭代             For In

1. 减法重载

class Number:  
  def __init__(self, start):  
    self.data = start  
  def __sub__(self, other): #minus method  
    return Number(self.data - other)  
number = Number(20)  
y = number ? 10 # invoke __sub__ method 
class Number: 
  def __init__(self, start): 
    self.data = start 
  def __sub__(self, other): #minus method 
    return Number(self.data - other) 
number = Number(20) 
y = number ? 10 # invoke __sub__ method

2. 迭代重载

class indexer:  
  def __getitem__(self, index): #iter override  
    return index ** 2 
X = indexer()  
X[2]  
for i in range(5):  
  print X[i] 
class indexer: 
  def __getitem__(self, index): #iter override 
    return index ** 2 
X = indexer() 
X[2] 
for i in range(5): 
  print X[i]

3. 索引重载

class stepper:  
  def __getitem__(self, i):  
    return self.data[i]  
X = stepper()  
X.data = 'Spam' 
X[1] #call __getitem__  
for item in X: #call __getitem__  
  print item 
class stepper: 
  def __getitem__(self, i): 
    return self.data[i] 
X = stepper() 
X.data = 'Spam' 
X[1] #call __getitem__ 
for item in X: #call __getitem__ 
   print item

4. getAttr/setAttr重载

class empty:  
  def __getattr__(self,attrname):  
    if attrname == 'age':  
      return 40 
    else:  
      raise AttributeError,attrname  
X = empty()  
print X.age #call__getattr__  
class accesscontrol:  
  def __setattr__(self, attr, value):  
    if attr == 'age':  
      # Self.attrname = value loops!  
      self.__dict__[attr] = value  
    else:  
      print attr  
      raise AttributeError, attr + 'not allowed' 
X = accesscontrol()  
X.age = 40   #call __setattr__  
X.name = 'wang' #raise exception 
class empty: 
  def __getattr__(self,attrname): 
    if attrname == 'age': 
      return 40 
    else: 
      raise AttributeError,attrname 
X = empty() 
print X.age #call__getattr__ 
class accesscontrol: 
  def __setattr__(self, attr, value): 
    if attr == 'age': 
      # Self.attrname = value loops! 
      self.__dict__[attr] = value 
    else: 
      print attr 
      raise AttributeError, attr + 'not allowed' 
X = accesscontrol() 
X.age = 40   #call __setattr__ 
X.name = 'wang' #raise exception

5. 打印重载

class adder:  
  def __init__(self, value=0):  
    self.data = value  
  def __add__(self, other):  
    self.data += other  
class addrepr(adder):  
  def __repr__(self):  
    return 'addrepr(%s)' % self.data  
x = addrepr(2) #run __init__  
x + 1    #run __add__  
print x   #run __repr__ 
class adder: 
  def __init__(self, value=0): 
    self.data = value 
  def __add__(self, other): 
    self.data += other 
class addrepr(adder): 
  def __repr__(self): 
    return 'addrepr(%s)' % self.data 
x = addrepr(2) #run __init__ 
x + 1    #run __add__ 
print x   #run __repr__

6. Call调用函数重载

class Prod:  
  def __init__(self, value):  
    self.value = value  
  def __call__(self, other):  
    return self.value * other  
p = Prod(2) #call __init__  
print p(1) #call __call__  
print p(2) 
class Prod: 
  def __init__(self, value): 
    self.value = value 
  def __call__(self, other): 
    return self.value * other 
p = Prod(2) #call __init__ 
print p(1) #call __call__ 
print p(2)

7. 析构函数重载

class Life:  
  def __init__(self, name='name'):  
    print 'Hello', name  
    self.name = name  
  def __del__(self):  
    print 'Goodby', self.name  
brain = Life('Brain') #call __init__  
brain = 'loretta'  # call __del__

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
Python中optionParser模块的使用方法实例教程
Aug 29 Python
Python入门学习之字符串与比较运算符
Oct 12 Python
详解Python中使用base64模块来处理base64编码的方法
Jul 01 Python
Python中使用Counter进行字典创建以及key数量统计的方法
Jul 06 Python
Python numpy.array()生成相同元素数组的示例
Nov 12 Python
python3实现表白神器
Apr 09 Python
Python 处理文件的几种方式
Aug 23 Python
基于python的selenium两种文件上传操作实现详解
Sep 19 Python
用Python做一个久坐提醒小助手的示例代码
Feb 10 Python
Django框架models使用group by详解
Mar 11 Python
python实现TCP文件传输
Mar 20 Python
Pyqt5将多个类组合在一个界面显示的完整示例
Sep 04 Python
python使用Image处理图片常用技巧分析
Jun 01 #Python
python实现图片变亮或者变暗的方法
Jun 01 #Python
wxPython中listbox用法实例详解
Jun 01 #Python
在Python的Django框架下使用django-tagging的教程
May 30 #Python
使用url_helper简化Python中Django框架的url配置教程
May 30 #Python
在Python的Django框架中simple-todo工具的简单使用
May 30 #Python
Python中Django框架下的staticfiles使用简介
May 30 #Python
You might like
PHP中动态显示签名和ip原理
2007/03/28 PHP
php自动载入类用法实例分析
2016/06/24 PHP
Yii视图操作之自定义分页实现方法
2016/07/14 PHP
js控制分页打印、打印分页示例
2014/02/08 Javascript
javascript中一些util方法汇总
2015/06/10 Javascript
Bootstrap框架下下拉框select搜索功能
2020/03/26 Javascript
javascript-解决mongoose数据查询的异步操作
2016/12/22 Javascript
jQuery实现字符串全部替换的方法【推荐】
2017/03/09 Javascript
js禁止浏览器的回退事件
2017/04/20 Javascript
关于javascript作用域的常见面试题分享
2017/06/18 Javascript
jQuery实现的form转json经典示例
2017/10/10 jQuery
微信小程序局部刷新触发整页刷新效果的实现代码
2018/11/21 Javascript
浅谈Vue服务端渲染框架Nuxt的那些事
2018/12/21 Javascript
详解vue 中 scoped 样式作用域的规则
2020/09/14 Javascript
[01:10]DOTA2次级职业联赛 - Fly战队宣传片
2014/12/01 DOTA
使用Python制作获取网站目录的图形化程序
2015/05/04 Python
python中hashlib模块用法示例
2017/10/30 Python
在unittest中使用 logging 模块记录测试数据的方法
2018/11/30 Python
Python基于百度云文字识别API
2018/12/13 Python
Python符号计算之实现函数极限的方法
2019/07/15 Python
Python Django2.0集成Celery4.1教程
2019/11/19 Python
Python Web静态服务器非堵塞模式实现方法示例
2019/11/21 Python
PyQt5高级界面控件之QTableWidget的具体使用方法
2020/02/23 Python
Python实现敏感词过滤的4种方法
2020/09/12 Python
Python+unittest+requests 接口自动化测试框架搭建教程
2020/10/09 Python
Python爬虫开发与项目实战
2020/12/16 Python
重新定义牛仔布,100美元以下:Warp + Weft
2018/07/25 全球购物
艺术专业大学生自我评价
2013/09/22 职场文书
《雪儿》教学反思
2014/04/17 职场文书
班干部演讲稿
2014/04/24 职场文书
活动总结范文
2014/08/30 职场文书
护士个人年终总结
2015/02/13 职场文书
社区党员干部承诺书
2015/05/04 职场文书
远程教育集中轮训基层干部培训班学习心得体会
2016/01/09 职场文书
小学三年级语文教学反思
2016/03/03 职场文书
《巫师》是美食游戏?CDPR10月将推出《巫师》官方食谱
2022/04/03 其他游戏