python 魔法方法加减乘除

编程入门 行业动态 更新时间:2024-10-10 00:28:00

python 魔法方法<a href=https://www.elefans.com/category/jswz/34/1746413.html style=加减乘除"/>

python 魔法方法加减乘除

一、算术魔法方法的举例

1、加法(__add__)的算术运算调用减法(__sub__)的算术运算,减法(__sub__)的算术运算调用加法(__add__)的算术运算

class New_Init(int):

def __add__(self,other):return int.__sub__(self,other)

def __sub__(self,other):return int.__add__(self,other)>>> a = New_Init('5')>>> b = New_Init(6)>>> a+b-1

>>> a-b11

>>>

2、针对以上需求,现在要求不使用int方法进行运算

classTry_int(int):def __add__(self,other):return self+otherdef __sub__(self,other):return self+other>>> a = Try_int(5)>>> b = Try_int(6)>>> a+b

Traceback (most recent call last):

File"", line 1, in a+b

File"/Users/wufq/Desktop/加法算术运算.py", line 3, in __add__

return self+other

File"/Users/wufq/Desktop/加法算术运算.py", line 3, in __add__

return self+other

File"/Users/wufq/Desktop/加法算术运算.py", line 3, in __add__

return self+other

[Previous line repeated990more times]

RecursionError: maximum recursion depth exceeded#不使用int会使程序一直进行递归运算,导致内存不足

#程序改进

classTry_int(int):def __add__(self,other):return int(self)+int(other)def __sub__(self,othe

更多推荐

python 魔法方法加减乘除

本文发布于:2024-02-05 17:07:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1745513.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加减乘除   方法   魔法   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!