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中的cookielib模拟登录网站
Apr 09 Python
详解Python3操作Mongodb简明易懂教程
May 25 Python
python实现ID3决策树算法
Dec 20 Python
浅谈Python中的作用域规则和闭包
Mar 20 Python
致Python初学者 Anaconda入门使用指南完整版
Apr 05 Python
Python闭包函数定义与用法分析
Jul 20 Python
使用EduBlock轻松学习Python编程
Oct 08 Python
python2 中 unicode 和 str 之间的转换及与python3 str 的区别
Jul 25 Python
tensorflow 实现自定义梯度反向传播代码
Feb 10 Python
Python爬虫后获取重定向url的两种方法
Jan 19 Python
简述python四种分词工具,盘点哪个更好用?
Apr 13 Python
python 进阶学习之python装饰器小结
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
通过文字传递创建的图形按钮
2006/10/09 PHP
php合并数组array_merge函数运算符加号与的区别
2008/10/31 PHP
基于HBase Thrift接口的一些使用问题及相关注意事项的详解
2013/06/03 PHP
Yii使用CLinkPager分页实例详解
2014/07/23 PHP
用PHP将Unicode 转化为UTF-8的实现方法(推荐)
2017/02/08 PHP
不错的asp中显示新闻的功能
2006/10/13 Javascript
javascript时间函数基础介绍
2013/03/28 Javascript
jquery 添加节点的几种方法介绍
2013/09/04 Javascript
js实现当复选框选择匿名登录时隐藏登录框效果
2015/08/14 Javascript
JS实现超简单的仿QQ折叠菜单效果
2015/09/21 Javascript
详解JavaScript异步编程中jQuery的promise对象的作用
2016/05/03 Javascript
jquery属性,遍历,HTML操作方法详解
2016/09/17 Javascript
使用微信内嵌H5网页解决JS倒计时失效问题
2017/01/13 Javascript
Webpack优化配置缩小文件搜索范围
2017/12/25 Javascript
手把手教你vue-cli单页到多页应用的方法
2018/05/31 Javascript
微信小程序适配iphoneX的实现方法
2018/09/18 Javascript
如何为vuex实现带参数的 getter和state.commit
2019/01/04 Javascript
Vue Element UI + OSS实现上传文件功能
2019/07/31 Javascript
JavaScript基于SVG的图片切换效果实例代码
2020/12/15 Javascript
python实现超简单端口转发的方法
2015/03/13 Python
python中Flask框架简单入门实例
2015/03/21 Python
使用Python装饰器在Django框架下去除冗余代码的教程
2015/04/16 Python
Python使用combinations实现排列组合的方法
2018/11/13 Python
浅谈django2.0 ForeignKey参数的变化
2019/08/06 Python
Python (Win)readline和tab补全的安装方法
2019/08/27 Python
wxpython布局的实现方法
2019/11/01 Python
wxPython实现分隔窗口
2019/11/19 Python
python 操作excel表格的方法
2020/12/05 Python
Python+unittest+requests+excel实现接口自动化测试框架
2020/12/23 Python
英国马莎百货官网:Marks & Spencer
2016/07/29 全球购物
美国葡萄酒网上商店:Martha Stewart Wine Co.
2019/03/17 全球购物
C有"按引用传递"吗
2016/09/06 面试题
《燕子》教学反思
2014/02/18 职场文书
团员个人年度总结
2015/02/26 职场文书
员工开除通知书
2015/04/25 职场文书
《自己的花是让别人看的》教学反思
2016/02/19 职场文书