首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

Python魔法之旅-魔法方法(09)

  • 25-03-03 05:08
  • 3077
  • 8218
blog.csdn.net

目录

一、概述

1、定义

2、作用

二、应用场景

1、构造和析构

2、操作符重载

3、字符串和表示

4、容器管理

5、可调用对象

6、上下文管理

7、属性访问和描述符

8、迭代器和生成器

9、数值类型

10、复制和序列化

11、自定义元类行为

12、自定义类行为

13、类型检查和转换

14、自定义异常

三、学习方法

1、理解基础

2、查阅文档

3、编写示例

4、实践应用

5、阅读他人代码

6、参加社区讨论

7、持续学习

8、练习与总结

9、注意兼容性

10、避免过度使用

四、魔法方法

29、__iadd__方法

29-1、语法

29-2、参数

29-3、功能

29-4、返回值

29-5、说明

29-6、用法

30、__iand__方法

30-1、语法

30-2、参数

30-3、功能

30-4、返回值

30-5、说明

30-6、用法

31、__imul__方法

31-1、语法

31-2、参数

31-3、功能

31-4、返回值

31-5、说明

31-6、用法

五、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、博客个人主页

一、概述

1、定义

        魔法方法(Magic Methods/Special Methods,也称特殊方法或双下划线方法)是Python中一类具有特殊命名规则的方法,它们的名称通常以双下划线(`__`)开头和结尾。

        魔法方法用于在特定情况下自动被Python解释器调用,而不需要显式地调用它们,它们提供了一种机制,让你可以定义自定义类时具有与内置类型相似的行为。

2、作用

        魔法方法允许开发者重载Python中的一些内置操作或函数的行为,从而为自定义的类添加特殊的功能。

二、应用场景

1、构造和析构

1-1、__init__(self, [args...]):在创建对象时初始化属性。
1-2、__new__(cls, [args...]):在创建对象时控制实例的创建过程(通常与元类一起使用)。
1-3、__del__(self):在对象被销毁前执行清理操作,如关闭文件或释放资源。

2、操作符重载

2-1、__add__(self, other)、__sub__(self, other)、__mul__(self, other)等:自定义对象之间的算术运算。
2-2、__eq__(self, other)、__ne__(self, other)、__lt__(self, other)等:定义对象之间的比较操作。

3、字符串和表示

3-1、__str__(self):定义对象的字符串表示,常用于print()函数。
3-2、__repr__(self):定义对象的官方字符串表示,用于repr()函数和交互式解释器。

4、容器管理

4-1、__getitem__(self, key)、__setitem__(self, key, value)、__delitem__(self, key):用于实现类似列表或字典的索引访问、设置和删除操作。
4-2、__len__(self):返回对象的长度或元素个数。

5、可调用对象

5-1、__call__(self, [args...]):允许对象像函数一样被调用。

6、上下文管理

6-1、__enter__(self)、__exit__(self, exc_type, exc_val, exc_tb):用于实现上下文管理器,如with语句中的对象。

7、属性访问和描述符

7-1、__getattr__, __setattr__, __delattr__:这些方法允许对象在访问或修改不存在的属性时执行自定义操作。
7-2、描述符(Descriptors)是实现了__get__, __set__, 和__delete__方法的对象,它们可以控制对另一个对象属性的访问。

8、迭代器和生成器

8-1、__iter__和__next__:这些方法允许对象支持迭代操作,如使用for循环遍历对象。
8-2、__aiter__, __anext__:这些是异步迭代器的魔法方法,用于支持异步迭代。

9、数值类型

9-1、__int__(self)、__float__(self)、__complex__(self):定义对象到数值类型的转换。
9-2、__index__(self):定义对象用于切片时的整数转换。

10、复制和序列化

10-1、__copy__和__deepcopy__:允许对象支持浅复制和深复制操作。
10-2、__getstate__和__setstate__:用于自定义对象的序列化和反序列化过程。

11、自定义元类行为

11-1、__metaclass__(Python 2)或元类本身(Python 3):允许自定义类的创建过程,如动态创建类、修改类的定义等。

12、自定义类行为

12-1、__init__和__new__:用于初始化对象或控制对象的创建过程。
12-2、__init_subclass__:在子类被创建时调用,允许在子类中执行一些额外的操作。

13、类型检查和转换

13-1、__instancecheck__和__subclasscheck__:用于自定义isinstance()和issubclass()函数的行为。

14、自定义异常

14-1、你可以通过继承内置的Exception类来创建自定义的异常类,并定义其特定的行为。

三、学习方法

        要学好Python的魔法方法,你可以遵循以下方法及步骤:

1、理解基础

        首先确保你对Python的基本语法、数据类型、类和对象等概念有深入的理解,这些是理解魔法方法的基础。

2、查阅文档

        仔细阅读Python官方文档中关于魔法方法的部分,文档会详细解释每个魔法方法的作用、参数和返回值。你可以通过访问Python的官方网站或使用help()函数在Python解释器中查看文档。

3、编写示例

        为每个魔法方法编写简单的示例代码,以便更好地理解其用法和效果,通过实际编写和运行代码,你可以更直观地感受到魔法方法如何改变对象的行为。

4、实践应用

        在实际项目中尝试使用魔法方法。如,你可以创建一个自定义的集合类,使用__getitem__、__setitem__和__delitem__方法来实现索引操作。只有通过实践应用,你才能更深入地理解魔法方法的用途和重要性。

5、阅读他人代码

        阅读开源项目或他人编写的代码,特别是那些使用了魔法方法的代码,这可以帮助你学习如何在实际项目中使用魔法方法。通过分析他人代码中的魔法方法使用方式,你可以学习到一些新的技巧和最佳实践。

6、参加社区讨论

        参与Python社区的讨论,与其他开发者交流关于魔法方法的使用经验和技巧,在社区中提问或回答关于魔法方法的问题,这可以帮助你更深入地理解魔法方法并发现新的应用场景。

7、持续学习

        Python语言和其生态系统不断发展,新的魔法方法和功能可能会不断被引入,保持对Python社区的关注,及时学习新的魔法方法和最佳实践。

8、练习与总结

        多做练习,通过编写各种使用魔法方法的代码来巩固你的理解,定期总结你学到的知识和经验,形成自己的知识体系。

9、注意兼容性

        在使用魔法方法时,要注意不同Python版本之间的兼容性差异,确保你的代码在不同版本的Python中都能正常工作。

10、避免过度使用

        虽然魔法方法非常强大,但过度使用可能会导致代码难以理解和维护,在编写代码时,要权衡使用魔法方法的利弊,避免滥用。

        总之,学好Python的魔法方法需要不断地学习、实践和总结,只有通过不断地练习和积累经验,你才能更好地掌握这些强大的工具,并在实际项目中灵活运用它们。

四、魔法方法

29、__iadd__方法

29-1、语法
  1. __iadd__(self, other, /)
  2. Implement self += other
29-2、参数

29-2-1、self(必须):一个对实例对象本身的引用,在类的所有方法中都会自动传递。

29-2-2、other(必须):除self外,参与增量赋值操作的另一个参数,即+=运算符右侧的参数。

29-2-3、/(可选):这是从Python 3.8开始引入的参数注解语法,它表示这个方法不接受任何位置参数(positional-only parameters)之后的关键字参数(keyword arguments)。

29-3、功能

        用于定义当对象使用+=运算符进行增量赋值时的行为。

29-4、返回值

        返回执行增量赋值后的对象(通常是self本身)。

29-5、说明

        无

29-6、用法
  1. # 029、__iadd__方法:
  2. # 1、整数累加器
  3. class IntAccumulator:
  4. def __init__(self, start=0):
  5. self.value = start
  6. def __iadd__(self, other):
  7. self.value += other
  8. return self
  9. if __name__ == '__main__':
  10. acc = IntAccumulator(5)
  11. acc += 3 # acc.value 现在为 8
  12. # 2、字符串拼接器
  13. class StringJoiner:
  14. def __init__(self, start=""):
  15. self.value = start
  16. def __iadd__(self, other):
  17. self.value += other
  18. return self
  19. if __name__ == '__main__':
  20. sj = StringJoiner("Hello")
  21. sj += " World" # sj.value 现在为 "Hello World"
  22. # 3、列表合并器
  23. class ListMerger:
  24. def __init__(self, start=[]):
  25. self.value = start
  26. def __iadd__(self, other):
  27. self.value.extend(other)
  28. return self
  29. if __name__ == '__main__':
  30. lm = ListMerger([1, 2])
  31. lm += [3, 4] # lm.value 现在为 [1, 2, 3, 4]
  32. # 4、字典合并
  33. class DictMerger:
  34. def __init__(self, start={}):
  35. self.value = start
  36. def __iadd__(self, other):
  37. self.value.update(other)
  38. return self
  39. if __name__ == '__main__':
  40. dm = DictMerger({"a": 1})
  41. dm += {"b": 2} # dm.value 现在为 {"a": 1, "b": 2}
  42. # 5、坐标累加
  43. class Point:
  44. def __init__(self, x=0, y=0):
  45. self.x = x
  46. self.y = y
  47. def __iadd__(self, other):
  48. if isinstance(other, Point):
  49. self.x += other.x
  50. self.y += other.y
  51. return self
  52. raise TypeError("Unsupported operand type for +=")
  53. if __name__ == '__main__':
  54. p = Point(1, 2)
  55. p += Point(3, 4) # p.x 现在为 4, p.y 现在为 6
  56. # 6、计数器
  57. class Counter:
  58. def __init__(self, start=0):
  59. self.value = start
  60. def __iadd__(self, other):
  61. if isinstance(other, int):
  62. self.value += other
  63. return self
  64. raise TypeError("Unsupported operand type for +=")
  65. def increment(self):
  66. self.value += 1
  67. if __name__ == '__main__':
  68. c = Counter(5)
  69. c += 3 # c.value 现在为 8
  70. # 7、自定义时间累加
  71. from datetime import timedelta
  72. class CustomTimeDelta:
  73. def __init__(self, days=0, seconds=0):
  74. self.delta = timedelta(days=days, seconds=seconds)
  75. def __iadd__(self, other):
  76. if isinstance(other, CustomTimeDelta):
  77. self.delta += other.delta
  78. return self
  79. raise TypeError("Unsupported operand type for +=")
  80. if __name__ == '__main__':
  81. td = CustomTimeDelta(1, 30)
  82. td += CustomTimeDelta(0, 60) # td.delta 现在为 1 day, 1:30:00
  83. # 8、复数累加
  84. class ComplexNumber:
  85. def __init__(self, real=0, imag=0):
  86. self.real = real
  87. self.imag = imag
  88. def __iadd__(self, other):
  89. if isinstance(other, ComplexNumber):
  90. self.real += other.real
  91. self.imag += other.imag
  92. return self
  93. raise TypeError("Unsupported operand type for +=")
  94. if __name__ == '__main__':
  95. cn = ComplexNumber(1, 2)
  96. cn += ComplexNumber(3, 4) # cn.real 现在为 4, cn.imag 现在为 6
  97. # 9、银行账户存款累加
  98. class BankAccount:
  99. def __init__(self, balance=0):
  100. self.balance = balance
  101. def __iadd__(self, other):
  102. if isinstance(other, (int, float)):
  103. self.balance += other
  104. return self
  105. raise TypeError("Unsupported operand type for +=")
  106. def get_balance(self):
  107. return self.balance
  108. if __name__ == '__main__':
  109. acct = BankAccount(1000)
  110. acct += 500 # acct.balance 现在为 1500
  111. # 10、分数累加
  112. from fractions import Fraction
  113. class RationalNumber:
  114. def __init__(self, numerator=0, denominator=1):
  115. self.value = Fraction(numerator, denominator)
  116. def __iadd__(self, other):
  117. if isinstance(other, (int, float, Fraction, RationalNumber)):
  118. if isinstance(other, RationalNumber):
  119. other_value = other.value
  120. else:
  121. other_value = Fraction(other)
  122. self.value += other_value
  123. return self
  124. raise TypeError("Unsupported operand type for +=")
  125. def __str__(self):
  126. return str(self.value)
  127. if __name__ == '__main__':
  128. rn = RationalNumber(1, 2)
  129. rn += RationalNumber(1, 4) # rn 现在表示 3/4
  130. print(rn) # 输出: 3/4
  131. # 11、二维向量累加
  132. class Vector2D:
  133. def __init__(self, x=0, y=0):
  134. self.x = x
  135. self.y = y
  136. def __iadd__(self, other):
  137. if isinstance(other, Vector2D):
  138. self.x += other.x
  139. self.y += other.y
  140. return self
  141. raise TypeError("Unsupported operand type for +=")
  142. def __str__(self):
  143. return f"({self.x}, {self.y})"
  144. if __name__ == '__main__':
  145. v1 = Vector2D(1, 2)
  146. v2 = Vector2D(3, 4)
  147. v1 += v2 # v1 现在为 (4, 6)
  148. print(v1) # 输出: (4, 6)
  149. # 12、颜色混合(简化版)
  150. class Color:
  151. def __init__(self, red=0, green=0, blue=0):
  152. self.red = red
  153. self.green = green
  154. self.blue = blue
  155. def __iadd__(self, other):
  156. if isinstance(other, Color):
  157. self.red += other.red
  158. self.green += other.green
  159. self.blue += other.blue
  160. # 注意:这里可能需要额外的逻辑来确保 RGB 值在 0-255 范围内
  161. return self
  162. raise TypeError("Unsupported operand type for +=")
  163. def __str__(self):
  164. return f"RGB({self.red}, {self.green}, {self.blue})"
  165. if __name__ == '__main__':
  166. red = Color(255, 0, 0)
  167. blue = Color(0, 0, 255)
  168. red += blue # 注意:这会导致 RGB 值超过 255,只是一个简化的例子
  169. print(red) # 输出: RGB(510, 0, 510),但实际应用中需要处理溢出

30、__iand__方法

30-1、语法
  1. __iand__(self, other, /)
  2. Return self &= other
30-2、参数

30-2-1、self(必须):一个对实例对象本身的引用,在类的所有方法中都会自动传递。

30-2-2、other(必须):除self外,参与按位与操作的另一个参数,即&=运算符右侧的参数。

30-2-3、/(可选):这是从Python 3.8开始引入的参数注解语法,它表示这个方法不接受任何位置参数(positional-only parameters)之后的关键字参数(keyword arguments)。

30-3、功能

        用于定义当对象使用&=运算符进行按位与赋值时的行为。

30-4、返回值

        返回执行按位与赋值后的对象(通常是self本身),以支持链式赋值。

30-5、说明

        无

30-6、用法
  1. # 030、__iand__方法:
  2. # 1、二进制字符串类
  3. class BinaryString:
  4. def __init__(self, s):
  5. self.s = ''.join(format(ord(c), '08b') for c in s)
  6. def __iand__(self, other):
  7. if isinstance(other, BinaryString):
  8. self.s = ''.join(str(int(a) & int(b)) for a, b in zip(self.s, other.s))
  9. return self
  10. raise TypeError("Unsupported operand type(s) for &=: 'BinaryString' and '{}'".format(type(other).__name__))
  11. def __str__(self):
  12. return self.s
  13. # 2、权限类(例如Unix权限)
  14. class Permissions:
  15. def __init__(self, value):
  16. self.value = value
  17. def __iand__(self, other):
  18. if isinstance(other, Permissions):
  19. self.value &= other.value
  20. return self
  21. raise TypeError("Unsupported operand type(s) for &=: 'Permissions' and '{}'".format(type(other).__name__))
  22. # ... 其他方法,如 __str__, __int__ 等 ...
  23. # 3、颜色类(使用RGB值)
  24. class Color:
  25. def __init__(self, r, g, b):
  26. self.r = r
  27. self.g = g
  28. self.b = b
  29. def __iand__(self, other):
  30. if isinstance(other, Color):
  31. self.r &= other.r
  32. self.g &= other.g
  33. self.b &= other.b
  34. return self
  35. raise TypeError("Unsupported operand type(s) for &=: 'Color' and '{}'".format(type(other).__name__))
  36. # ... 其他方法,如 __str__, __repr__ 等 ...

31、__imul__方法

31-1、语法
  1. __imul__(self, other, /)
  2. Implement self *= other
31-2、参数

31-2-1、self(必须):一个对实例对象本身的引用,在类的所有方法中都会自动传递。

31-2-2、other(必须):除self外,参与乘法赋值操作的另一个参数,即*=运算符右侧的参数。

31-2-3、/(可选):这是从Python 3.8开始引入的参数注解语法,它表示这个方法不接受任何位置参数(positional-only parameters)之后的关键字参数(keyword arguments)。

31-3、功能

        用于定义当对象使用*=运算符进行乘法赋值时的行为。

31-4、返回值

        返回执行乘法赋值后的对象(通常是 self 本身),以支持链式赋值。

31-5、说明

        无

31-6、用法
  1. # 031、__imul__方法:
  2. # 1、向量类
  3. class Vector:
  4. def __init__(self, *args):
  5. self.data = list(args)
  6. def __imul__(self, other):
  7. if isinstance(other, (int, float)):
  8. self.data = [x * other for x in self.data]
  9. return self
  10. raise TypeError("Unsupported operand type(s) for *=: 'Vector' and '{}'".format(type(other).__name__))
  11. def __str__(self):
  12. return str(self.data)
  13. if __name__ == '__main__':
  14. v = Vector(1, 2, 3)
  15. v *= 2 # v 现在为 [2, 4, 6]
  16. print(v)
  17. # 2、矩阵类
  18. class Matrix:
  19. def __init__(self, data):
  20. self.data = data
  21. def __imul__(self, other):
  22. if isinstance(other, (int, float)):
  23. self.data = [[x * other for x in row] for row in self.data]
  24. return self
  25. raise TypeError("Unsupported operand type(s) for *=: 'Matrix' and '{}'".format(type(other).__name__))
  26. # 假设 data 是一个二维列表
  27. # ... 其他矩阵操作 ...
  28. if __name__ == '__main__':
  29. m = Matrix([[1, 2], [3, 4]])
  30. m *= 2 # m 现在为 [[2, 4], [6, 8]]
  31. # 3、复数类
  32. class Complex:
  33. def __init__(self, real, imag):
  34. self.real = real
  35. self.imag = imag
  36. def __imul__(self, other):
  37. if isinstance(other, (int, float, complex)):
  38. if isinstance(other, complex):
  39. self.real, self.imag = (self.real * other.real - self.imag * other.imag,
  40. self.real * other.imag + self.imag * other.real)
  41. else:
  42. self.real *= other
  43. self.imag *= other
  44. return self
  45. raise TypeError("Unsupported operand type(s) for *=: 'Complex' and '{}'".format(type(other).__name__))
  46. # ... 其他复数操作 ...
  47. if __name__ == '__main__':
  48. c = Complex(1, 2)
  49. c *= 2 # c 现在为 (2, 4)

五、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、博客个人主页

文章知识点与官方知识档案匹配,可进一步学习相关知识
Python入门技能树首页概览425874 人正在系统学习中
遨游码海,我心飞扬
微信名片
注:本文转载自blog.csdn.net的神奇夜光杯的文章"https://myelsa1024.blog.csdn.net/article/details/139375140"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2491) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top