042魔法方法:算术运算

自python2.2以后,对类和类型进行了统一,
   做法就是将int(),float(),str(),list(),tuple()转为工厂函数
   工厂函数:就是一个对象,当你调用它们的时候,事实上就是创建一个相应的实例对象
   如:>>>a = int(‘123‘)
       >>>b = int(‘456‘)
       >>>a + b
       579
       a和b是工厂函数(类对象),int的实例对象
       对象a和b相加的时候会自动调用__add__魔法函数

算术运算对应的魔法函数:
__add__(self,other)      定义加法的行为:+
__sub__(self,other)      定义减法的行为:-
__mul__(self,other)      定义乘法的行为:*
__truediv__(self,other)  定义真除法的行为:/
__floordiv__(self,other) 定义整数除法的行为://
__mod__(self,other)      定义取模运算的行为:%
__divmod__(self,other)   定义被divmod()调用时的行为
__pow__(self,other[,modulo])定义被power()调用或**运算时的行为
__lshift__(self,other)   定义按位左移的行为:<<
__rshift__(self,other)   定义按位右移的行为:>>
__add__(self,other)      定义加法的行为:&
__xor__(self,other)      定义加法的行为:^
__or__(self,other)       定义加法的行为:|

例如:>>> class New_int(int):
      ...     def __add__(self,other):
      ...          return int.__sub__(self,other)
      ...     def __sub__(self,other):
      ...          return int.__add__(self,other)
      ...
      >>> a = New_int(3)
      >>> b = New_int(5)
      >>> a+b
      -2
      >>> a-b
      8
如果返回时不调用int的魔法方法可以吗?
      >>> class New_int(int):
      ...     def __add__(self,other):
      ...         return self + other
      ...     def __sub__(self,other):
      ...         return self - other
      ...
      >>> a = New_int(3)
      >>> b = New_int(5)
      >>> a + b                      会无限递归,然后退出
      File "<stdin>", line 3, in __add__
      ............
      File "<stdin>", line 3, in __add__
      RuntimeError: maximum recursion depth exceeded while calling a Python object

可以修改一下:
      >>> class Try_int(int):
      ...     def __add__(self,other):
      ...         return int(self) + int(other)
      ...     def __sub__(self,other):
      ...         return int(self) - int(other)
      ...
      >>> a = Try_int(3)
      >>> b = Try_int(5)
      >>> a + b
      >>>8

练习:
1. python中可以实现两个字符串相加自动拼接,但两个字符串相减却抛出异常
   现在定义一个Nstr类,支持:A-B:从A中除去所有B的子字符串
如:>>> class Nstr(str):
   ...     def __sub__(self,other):
   ...         return self.replace(other,‘‘)
   ...
   >>> a = Nstr("123aaa")
   >>> b = Nstr("a")
   >>> a - b
   ‘123‘
   重载__sub__魔法方法即可

2. 移位操作符应用二进制操作数,定义一个新的类Nstr,也支持以为操作符的运算
如:>>> class Nstr(str):
   ...     def __lshift__(self,other):
   ...         return self[other:] + self[:other]
   ...     def __rshift__(self,other):
   ...         return self[:-other] + self[-other:]
   ...
   >>> a = Nstr(‘I love you!‘)
   >>> a << 3
   ‘ove you!I l‘
   >>> a >> 3
   ‘I love you!‘

3. 定义一个类Nstr,当类的实例对象发生+-*/时,将对象的所有字符串的ASCII码之和进行计算。
>>> class Nstr(int):
...     def __new__(cls,arg=0):
...         if isinstance(arg,str):
...             total = 0
...             for each in arg:
...                 total += ord(each)
...             arg = total
...         return int.__new__(cls,arg)
...
>>> a = Nstr(‘I‘)
>>> b = Nstr(‘LOVE‘)
>>> c = Nstr(‘YOU‘)
>>> a + b + c
636

时间: 2024-08-01 10:43:52

042魔法方法:算术运算的相关文章

043魔法方法:算术运算2

反运算:  当左操作数不支持响应的操作时被调用  如:对象(a+b),如果a对象有__add__方法,b对象的__radd__不会被调用      只有当a对象的__add__方法没有实现或者不支持相应的操作才会调用b的__radd__方法 如:>>> class Nint(int):      ...     def __radd__(self,other):      ...         return int.__sub__(self,other)      ...      

python_魔法方法(二):算术运算

python2.2之后,对类和类型做了同意,将int().float().str().list().touple()这些BIF转换为工厂函数 >>> type(len) <class 'builtin_function_or_method'> >>> type(int) <class 'type'> >>> type(dir) <class 'builtin_function_or_method'> >>

Python基础教程(第九章 魔法方法、属性和迭代器)

本文内容全部出自<Python基础教程>第二版,在此分享自己的学习之路. ______欢迎转载:http://www.cnblogs.com/Marlowes/p/5437223.html______ Created on Marlowes 在Python中,有的名称会在前面和后面都加上两个下划线,这种写法很特别.前面几章中已经出现过一些这样的名称(如__future__),这种拼写表示名字有特殊含义,所以绝不要在自己的程序中使用这样的名字.在Python中,由这些名字组成的集合所包含的方法称

&lt;&lt;Python基础教程&gt;&gt;学习笔记 | 第09章 | 魔法方法、属性和迭代器

这一章,有点抽象,看着有点蛋疼! 双下划线__future__或单下划线有特殊含义,在Python中,这些名字的集合称为魔法方法:最重要的是__init__和一些处理访问对象的方法,这些方法允许你创建自己的序列或者是映射. ------ 准备工作: 将__metaclass__=type放在模块的最开始位置,以确保类时最新式的.考虑下面两个类 class NewStyle(object): more_code_here class OldStyle: more_code_here 如果文件以__

python魔法方法详解

文章来源:http://blog.csdn.net/koko66/article/details/42709279 据说,Python 的对象天生拥有一些神奇的方法,它们总被双下划线所包围,他们是面向对象的 Python 的一切. 他们是可以给你的类增加魔力的特殊方法,如果你的对象实现(重载)了这些方法中的某一个,那么这个方法就会在特殊的情况下被 Python 所调用,你可以定义自己想要的行为,而这一切都是自动发生的. Python 的魔术方法非常强大,然而随之而来的则是责任.了解正确的方法去使

python魔法方法-反射运算和增量运算

反射运算 什么是反射运算符,其实就是反转了两个对象,下面先看一个普通运行符的实现: class Foo(object): def __init__(self, x): self.x = x def __add__(self, other): return 'Foo:%s + %s' % (self.x, other.x) class Boo(object): def __init__(self, x): self.x = x def __add__(self, other): return 'B

Python类属性访问的魔法方法

Python类属性访问的魔法方法: 1. __getattr__(self, name)- 定义当用户试图获取一个不存在的属性时的行为 2. __getattribute__(self, name)- 定义当该类的属性被访问时的行为 注意:当__getattr__与__getattribute__同时重写时,访问属性时,优先调用__getattribute__,只有当被访问的属性不存在时才触发__getattr__ 3. __setattr__(self, name, value)- 定义当一个

《Python基础教程》 读书笔记 第九章 魔法方法、属性和迭代器(上)

构造方法 在Python中创建一个构造方法很容易.只要把init方法的名字从简单的init修改为魔法版本__init__即可: >>> class FooBar: ...     def __init__(self): ...         self.somevar=42 ... >>> f=FooBar() >>> f.somevar 42 给构造方法传几个参数 >>> class FooBar: ...     def __in

magic method细解python一直让我疑惑的几个常用魔法方法(上)

这里只分析几个可能会常用到的魔法方法,像__new__这种不常用的,用来做元类初始化的或者是__init__这种初始化使用的 每个人都会用的就不介绍了. 其实每个魔法方法都是在对内建方法的重写,和做像装饰器一样的行为.理解这个道理 再尝试去理解每个细节装饰器会比较方便. 关于__str__和__repr__: 直接上例子: class Test(object): def __init__(self, world): self.world = world def __str__(self): re