当前位置: 首页 > 网络知识

Python基础入门学习笔记 042 魔法方法:算术运算

时间:2026-01-29 09:25:54
python2.2以后,对类和类型进行了统一,做法就是讲int()、float()、str()、list()、tuple()这些BIF转换为工厂函数(类对象): 1 >>> type(len) 2 <class 'builtin_function_or_method'> #普通的BIF 3 >>> type(int) 4 <class 'type'> #工厂函数(类对象),当调用它们的时候,其实就是创建了一个相应的实例对象 5 >>> type(dir) 6 <class 'builtin_function_or_method'> 7 >>> type(list) 8 <class 'type'> 9 10 >>> a = int('123') #创建一个相应的实例对象a 11 >>> b = int('345') 12 >>> a + b #python在两个对象进行相加操作 13 468

举个例子,下面定义一个比较特立独行的类:

1 >>> class New_int(int): 2 def __add__(self,other): 3 return int.__sub__(self,other) 4 def __sub__(self,other): 5 return int.__add__(self,other) 6 7 8 >>> a = New_int(3) 9 >>> b = New_int(5) 10 >>> a + b #两个对象相加,触发 __add__(self,other)方法 11 2 12 >>> a b 13 8 14 >>>

实例2:

1 >>> class New_int(int): 2 def __add__(self,other): 3 return (int(self) + int(other)) #将self与other强制转换为整型,所以不会出现两个对象相加触发__add__()方法 4 def __sub__(self,other): 5 return (int(self) int(other)) 6 7 8 >>> a = New_int(3) 9 >>> b = New_int(5) 10 >>> a + b 11 8



上一篇:Python基础入门学习笔记 050 模块:模块就是程序
下一篇:Python基础入门学习笔记 067 GUI的终极选择:Tkinter4
python
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器
  • 英特尔第五代 Xeon CPU 来了:详细信息和行业反应
  • 由于云计算放缓引发扩张担忧,甲骨文股价暴跌
  • Web开发状况报告详细介绍可组合架构的优点
  • 如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳
  • 美光在数据中心需求增长后给出了强有力的预测
  • 2027服务器市场价值将接近1960亿美元
  • 生成式人工智能的下一步是什么?
  • 分享在外部存储上安装Ubuntu的5种方法技巧
  • 全球数据中心发展的关键考虑因素
  • 英特尔与 Vertiv 合作开发液冷 AI 处理器

    英特尔第五代 Xeon CPU 来了:详细信息和行业反应

    由于云计算放缓引发扩张担忧,甲骨文股价暴跌

    Web开发状况报告详细介绍可组合架构的优点

    如何使用 PowerShell 的 Get-Date Cmdlet 创建时间戳

    美光在数据中心需求增长后给出了强有力的预测

    2027服务器市场价值将接近1960亿美元

    生成式人工智能的下一步是什么?

    分享在外部存储上安装Ubuntu的5种方法技巧

    全球数据中心发展的关键考虑因素