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群发邮件实例代码
Jan 03 Python
Python中的defaultdict模块和namedtuple模块的简单入门指南
Apr 01 Python
Python常用算法学习基础教程
Apr 13 Python
致Python初学者 Anaconda入门使用指南完整版
Apr 05 Python
10个Python小技巧你值得拥有
Sep 29 Python
Python使用ctypes调用C/C++的方法
Jan 29 Python
Python实现ATM系统
Feb 17 Python
PageFactory设计模式基于python实现
Apr 14 Python
python datetime处理时间小结
Apr 16 Python
浅谈keras使用中val_acc和acc值不同步的思考
Jun 18 Python
Python3获取cookie常用三种方案
Oct 05 Python
python如何进行基准测试
Apr 26 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
真正面向对象编程:PHP5.01发布
2006/10/09 PHP
mysql 搜索之简单应用
2007/04/27 PHP
php对gzip文件或者字符串解压实例参考
2008/07/25 PHP
php 读取shell管道传输过来的内容
2010/03/01 PHP
PHP json格式和js json格式 js跨域调用实现代码
2012/09/08 PHP
destoon实现VIP排名一直在前面排序的方法
2014/08/21 PHP
3款值得推荐的微信开发开源框架
2014/10/28 PHP
PHP使用JpGraph绘制折线图操作示例【附源码下载】
2019/10/18 PHP
JS+DIV实现鼠标划过切换层效果的实例代码
2013/11/26 Javascript
Javascript 函数parseInt()转换时出现bug问题
2014/05/20 Javascript
js的回调函数详解
2015/01/05 Javascript
AngularJS基础 ng-model 指令详解及示例代码
2016/08/02 Javascript
vue-cli3.0 脚手架搭建项目的过程详解
2018/10/19 Javascript
微信小程序实现展示评分结果功能
2019/02/15 Javascript
微信网页登录逻辑与实现方法
2019/04/29 Javascript
用vue设计一个日历表
2020/12/03 Vue.js
python中urllib模块用法实例详解
2014/11/19 Python
python处理二进制数据的方法
2015/06/03 Python
浅谈python数据类型及类型转换
2017/12/18 Python
python中使用iterrows()对dataframe进行遍历的实例
2018/06/09 Python
Python使用import导入本地脚本及导入模块的技巧总结
2019/08/07 Python
Django 自定义分页器的实现代码
2019/11/24 Python
解决ROC曲线画出来只有一个点的问题
2020/02/28 Python
Html5移动端获奖无缝滚动动画实现示例
2018/06/25 HTML / CSS
解决Firefox下不支持outerHTML问题代码分享
2014/06/04 HTML / CSS
加拿大折扣、优惠券和交易网站:WagJag
2018/02/07 全球购物
ZWILLING双立人法国网上商店:德国刀具锅具厨具品牌
2019/08/28 全球购物
医学专业毕业生推荐信
2014/07/12 职场文书
集体生日活动方案
2014/08/18 职场文书
党员查摆剖析材料
2014/10/10 职场文书
服务承诺书
2015/01/19 职场文书
社区母亲节活动总结
2015/02/10 职场文书
教师个人总结范文
2015/02/11 职场文书
刑事上诉状(无罪)
2015/05/23 职场文书
大学生学习十八届五中全会精神心得体会
2016/01/05 职场文书
mybatis 解决从列名到属性名的自动映射失败问题
2021/06/30 Java/Android