python 基础——运算符重载
|
方法 |
重载 |
调用 |
| __init__ | 构造函数 | x = Class() |
| __del__ | 析构函数 | del x |
| __str__ | 打印 | print x |
| __call__ | 调用函数 | x(*args) |
| __getattr__ | 获取属性 | y = x.method |
| __setattr__ | 设置属性 | x.any = value |
| __getitem__ | 获取索引 | x[key] |
| __setitem__ | 设置新索引 | x[key] = value |
| __len__ | 长度 | len(x) |
| __iter__ | 迭代 | for item in x: |
| __add__ | 加 | x + y |
| __sub__ | 减 | x - y |
| __mul__ | 乘 | x * y |
| __radd__ | ||
| __iadd__ | 左加 += | x += y |
| __or__ | 或 | | x | y |
| __cmp__ | 比较 == | x == y |
| __lt__ | 小于 < | x < y |
| __eq__ | 等于 = | x = y |
减法重载
重载"-" 不同对象的减法处理
class Number:
def __init__(self,start):
self.data=start
def __sub__(self,other):
return Number(self.data-other)
number=Number(20)
y=number-10
print number.data, y.data
重载"-" 相同对象的减法处理
class Big :
def __init__(self,a,b):
self.a=a
self.b=b
def __sub__(self,other):#other不用事先制定类型,可以直接当做一个Big来用
return Big(self.a-other.a,self.b-other.b)
i=Big(20,12);
j=Big(23,4);
k=i-j;
print k.a ,k.b
重载"+"
class AddOperator :
def __init__(self,a,b):
self.a=a
self.b=b
def __add__(self,other):#other不用事先制定类型,可以直接当做一个Big来用
return Big(self.a+other.a,self.b+other.b)
i=AddOperator(20,12);
j=AddOperator(23,4);
k=i+j;
print k.a ,k.b
重载"+="
class AddOperator :
def __init__(self,a,b):
self.a=a
self.b=b
def __iadd__(self,other):#other不用事先制定类型,可以直接当做一个Big来用
return Big(self.a+other.a,self.b+other.b)
i=AddOperator(20,12);
j=AddOperator(23,4);
i+=j;
print i.a ,i.b
重载乘法
不同对象的乘法:
class MulOperator:
def __init__(self,a,b):
self.a=a
self.b=b
def __mul__(self,n):
return MulOperator(self.a*n,self.b*n)
i=MulOperator(20,5)
j=i*4.5
print j.a,j.b
索引重载
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 __setitem__(self, key,value): #iter override
self.mydict[key] = value
return self.mydict
X = indexer() X[2] = 'test' # 它等于调用 X.__setitem__(2, 'test')
打印重载
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(%d)"% self.data # %d ,%s都可以
x=addrepr(2)
x+1
print x ,repr(x)
i=3;
print "%s---%d"% (i, i)
调用重载
__call__相当与 X()
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)
析构重载 __del__
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__
重载"|"
class Mat :
def __init__(self,value):
self.age=value
def __or__(self,other):
return self.age!=0 and other.age!=0
a=Mat(10)
b=Mat(21)
c=Mat(0)
print a|b ,a|c
打印转换重载
class PrintOperator:
def __init__(self,a):
self.a=a
def __str__(self,b=50):
return "I am %s years old!" % self.a
i=PrintOperator(10)
print i, str(i)
长度重载
class lenOperator:
def __init__(self,a,b,c):
(self.a,self.b,self.c)=(a,b,c)
def __len__(self):
return 3
a=lenOperator(0,2,4)
print len(a)
cmp重载
class cmpOperator:
def __init__(self,a,b,c):
(self.a,self.b,self.c)=(a,b,c)
def __cmp__(self,other):
if self.a>other.a:
return 1
elif self.a<other.a:
return -1
elif self.b>other.b:
return 1
elif self.b<other.b:
return -1
elif self.c>self.c:
return 1
elif self.c<self.c:
return -1
elif self.c==self.c:
return 0
i=cmpOperator(1,2,3)
j=cmpOperator(2,4,5)
k=cmpOperator(2,4,5)
a=cmpOperator(1,4,5)
print cmp(i,j),cmp(j,k),cmp(a,i)
delattr重载
class delattrOperator(object):
def __init__(self,a,b):
(self.a,self.b)=(a,b)
def __delattr__(self,name):
print "del obj.%s" % name
object.__delattr__(self,name)
a=delattrOperator(1,2)
print a.a,a.b
del a.a
print a.b
# print a.a 打印a会出错,a已经被删除。
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
python 基础——运算符重载的更多相关文章
- Python学习 之三 Python基础&运算符
第三章:Python基础 & 运算符 3.1 内容回顾 & 补充 计算机基础 编码 字符串: "中国" "Hello" 字 符: 中 e 字 节 ...
- C++基础——运算符重载友元函数示例
一.前言 其实本人学习C++的目的,只是为了体会OOP设计思想,并为利用System Verilog验证复杂设计做准备.如果想要真正做点软件方面项目级的东西,还需要掌握其他高级语言和库.框架等知识.因 ...
- 分分钟钟学会Python -基础&运算符
day002 基础&运算符 1.循环语句 ### 1.循环格式 while 条件: print('') ''' while True: print('人生苦短,我用Python.') ''' ...
- Python基础运算符(算数、比较、赋值、逻辑、成员)
Python运算符有(算数运算符.比较运算符.赋值运算符.逻辑运算符.位运算符.成员运算符.身份运算符): 本程序包含算数.比较.赋值.逻辑.成员运算符. 1.运算符测试 #!/usr/bin/pyt ...
- Python基础------运算符
运算符类型 算数运算符 + 加 - 减 * 乘 / 除 %取余 ...
- python-运算符重载
1. __item__ class X: def __init__(self, data=None): self.data = data or [] # 同样可用于 dict def __setite ...
- Python 中的运算符重载
本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理 一种运算符对于不同类型的对象,有不同的使用方式.例如, + 用于整型对象,表示两个数相加:用于字符串 ...
- python运算符重载(二)
一.基础知识 定义:当类中提供了某个特殊名称的方法,在该类的实例出现在它们相关的表达式时,Python自动调用它们 特性: 1.运算符重载让类拦截常规的Python运算. 2.类可重载所有Python ...
- python运算符重载
python运算符重载就是在解释器使用对象内置操作前,拦截该操作,使用自己写的重载方法. 重载方法:__init__为构造函数,__sub__为减法表达式 class Number: def __in ...
随机推荐
- XML与DataSet相互转换,DataSet查询
以FileShare.Read形式读XML文件: string hotspotXmlStr = string.Empty; try { Stream fileStream = new FileStre ...
- 前端MVC学习总结(三)——AngularJS服务、路由、内置API、jQueryLite
一.服务 AngularJS功能最基本的组件之一是服务(Service).服务为你的应用提供基于任务的功能.服务可以被视为重复使用的执行一个或多个相关任务的代码块. AngularJS服务是单例对象, ...
- Pyqt5.2.1生成的.ui文件转换成.py
cmd C:\>pyuic5 ui文件路径 -o 要生成的py文件路径 如下: C:\>pyuic5 c:\python33\lib\site-packages\pyqt5\uic\log ...
- erlang启动参数
出自: http://blog.sina.com.cn/s/blog_96b8a154010123cc.html
- KMP算法初探
[edit by xingoo] kmp算法其实就是一种改进的字符串匹配算法.复杂度可以达到O(n+m),n是参考字符串长度,m是匹配字符串长度. 传统的算法,就是匹配字符串与参考字符串挨个比较,如果 ...
- php 扩展 redis
1.通过phpinfo 查看php的版本( 要注意php 是nts 还是ts 通过phpinfo(); 查看其中的 Thread Safety 项,这个项目就是查看是否是线程安全,如果是:enabl ...
- 【转】android出现注: 某些输入文件使用或覆盖了已过时的 API。 注: 有关详细信息, 请使用 -Xlint:deprecation 重新编译。 注: 某些输入文件使用了未经检查或不安全的操作。 注
使用Android studio打包应用程序出现如下错误: 注: 某些输入文件使用或覆盖了已过时的 API. 注: 有关详细信息, 请使用 -Xlint:deprecation 重新编译. 注: 某些 ...
- Mysql权限控制 - 允许用户远程连接
Mysql为了安全性,在默认情况下用户只允许在本地登录,可是在有此情况下,还是需要使用用户进行远程连接,因此为了使其可以远程需要进行如下操作: 一.允许root用户在任何地方进行远程登录,并具有所有库 ...
- 深入了解android平台的jni(一)
android中很多Java类都具有native接口,这些接口由本地实现,然后注册到系统中. 主要的JNI代码放在以下的路径中:frameworks/base/core/jni/,这个路径中的 ...
- Adding DTrace Probes to PHP Extensions
By cj on Dec 06, 2012 The powerful DTrace tracing facility has some PHP-specific probes that can b ...