前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >算数运算(第十六章)

算数运算(第十六章)

作者头像
天钧
发布2019-07-26 17:25:54
3270
发布2019-07-26 17:25:54
举报
文章被收录于专栏:渗透云笔记渗透云笔记

自Python2.2以后,对类和类型进行了同一,做法就是将int(),float(),str(),list()tuple()这些BIF转换为工厂函数

工厂函数

>>> type(len)
<class 'builtin_function_or_method'>
 #len方法用于返回参数的长度

他返回了一句<class 'builtin_function_or_method'>这是个普通的BIF返回的,看一下Int的返回格式

>>> type(int)
<class 'type'>
>>> type(str)
<class 'type'>
>>>

你会发现,它和class(类,撞了衫)如下

>>> class A:
...     pass
...
>>> type(A)
<class 'type'>
>>>

所谓的工厂函数,其实就是个class(类),调用时,其实就是实例化一个对象,如下

>>> a = int("123")
>>> b = int("456")
>>> a + b
579
>>>

算数操作符

列举一些常用的算数运算的魔法方法

魔法方法

含义

__add__(self,other)

定义加法的行为:+

__sub__(self,other)

定义减法行为:-

__mul__(self,other)

定义乘法行为;*

__truediv__(self.other)

定义除法行为://

__mod__(self,other)

定义取模算法行为;%

__divmod__(self,other)

定义当做调用__divmod__时的行为

__pow__(self,other[,,odulo])

定义被当做__pow_-调用或**运算时行为

__lshift__(self,other)

定义按位左移的行为;<<

__rshift__(self,other)

定义按位右移的行为;>>

__and__(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(4)
>>> b = New_int(5)
>>> a  +  b
-1
>>> a - b
9

如果自己写代码,不想调用Python的默认方案行吗?

肯定行啊,但是我们可能会疏忽

看下列代码

class Try_int(int):
     def __add__(self,other):
             return selt + other
     def __sub__(self,other):
             return self - other
            

大家不妨找找错

运行后

>>> a = Try_int(4)
>>> b = Try_int(6)
>>> a +b
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    a +b
  File "C:/Users/Administrator/Desktop/__add甲方.py", line 3, in __add__
    return selt + other
NameError: name 'selt' is not defined

程序出现了无限递归的情况,为什么

return selt + other

因为这串代码,当对象涉及到,加法时会调用__add__然后,又加法又调用,形成无限的递归。

怎么改

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(4)
>>> b = Try_int(6)
>>> a + b
10
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-06-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 渗透云笔记 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档