首页 最新 热门 推荐

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

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

  • 25-03-03 05:08
  • 3579
  • 10287
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、避免过度使用

四、魔法方法

53、__or__方法

53-1、语法

53-2、参数

53-3、功能

53-4、返回值

53-5、说明

53-6、用法

54、__pos__方法

54-1、语法

54-2、参数

54-3、功能

54-4、返回值

54-5、说明

54-6、用法

55、__pow__方法

55-1、语法

55-2、参数

55-3、功能

55-4、返回值

55-5、说明

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

四、魔法方法

53、__or__方法

53-1、语法
  1. __or__(self, other, /)
  2. Return self | other
53-2、参数

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

53-2-2、 other(必须):表示要对self对象执行按位或操作的对象。

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

53-3、功能

        用于定义对象之间的按位或(bitwise OR)操作。

53-4、返回值

        返回一个表示self和other之间按位或操作结果的对象。

53-5、说明

        无

53-6、用法
  1. # 053、__or__方法:
  2. # 1、简单整数类
  3. class IntWrapper:
  4. def __init__(self, value):
  5. self.value = value
  6. def __or__(self, other):
  7. if not isinstance(other, IntWrapper):
  8. raise TypeError("Unsupported operand types")
  9. return IntWrapper(self.value | other.value)
  10. def __repr__(self):
  11. return f"IntWrapper({self.value})"
  12. # 2、权限标志类
  13. class Permission:
  14. READ = 1
  15. WRITE = 2
  16. EXECUTE = 4
  17. def __init__(self, flags):
  18. self.flags = flags
  19. def __or__(self, other):
  20. return Permission(self.flags | other.flags)
  21. def __repr__(self):
  22. return f"Permission({self.flags})"
  23. # 3、颜色混合(RGB 示例)
  24. class RGBColor:
  25. def __init__(self, r, g, b):
  26. self.r = r
  27. self.g = g
  28. self.b = b
  29. def __or__(self, other):
  30. return RGBColor(self.r | other.r, self.g | other.g, self.b | other.b) # 注意:这不一定是颜色混合的合理方式
  31. def __repr__(self):
  32. return f"RGBColor({self.r}, {self.g}, {self.b})"
  33. # 4、时间范围合并
  34. from datetime import datetime, timedelta
  35. class TimeRange:
  36. def __init__(self, start, end):
  37. self.start = start
  38. self.end = end
  39. def __or__(self, other):
  40. # 简化的合并逻辑,仅适用于不重叠且按时间顺序排列的范围
  41. if self.end <= other.start:
  42. return TimeRange(self.start, max(self.end, other.end))
  43. raise ValueError("Ranges overlap or are not in order")
  44. def __repr__(self):
  45. return f"TimeRange({self.start}, {self.end})"
  46. # 5、集合类似物的合并
  47. class UniqueList:
  48. def __init__(self, items):
  49. self.items = list(set(items))
  50. def __or__(self, other):
  51. return UniqueList(self.items + list(set(other.items) - set(self.items)))
  52. def __repr__(self):
  53. return f"UniqueList({self.items})"
  54. # 6、图形界面的按钮状态
  55. class ButtonState:
  56. PRESSED = 1
  57. RELEASED = 0
  58. def __init__(self, state):
  59. self.state = state
  60. def __or__(self, other):
  61. # 假设这里是一个特殊的逻辑,例如“同时按下多个按钮”
  62. return ButtonState(self.state | other.state)
  63. def __repr__(self):
  64. return f"ButtonState({self.state})"
  65. # 7、网络包合并(简化示例)
  66. class Packet:
  67. def __init__(self, data):
  68. self.data = data
  69. def __or__(self, other):
  70. return Packet(self.data + other.data)
  71. def __repr__(self):
  72. return f"Packet({self.data})"
  73. # 8、选项类(例如命令行选项)
  74. class Option:
  75. A = 1
  76. B = 2
  77. def __init__(self, flags):
  78. self.flags = flags
  79. def __or__(self, other):
  80. return Option(self.flags | other.flags)
  81. def __repr__(self):
  82. return f"Option({self.flags})"
  83. # 9、游戏状态合并(例如合并两个玩家的状态)
  84. class GameState:
  85. def __init__(self, score, lives):
  86. self.score = score
  87. self.lives = lives
  88. def __or__(self, other):
  89. # 假设合并状态是取最高分和总生命数(不实际,仅为示例)
  90. return GameState(max(self.score, other.score), self.lives + other.lives)
  91. def __repr__(self):
  92. return f"GameState(score={self.score}, lives={self.lives})"
  93. # 10、自定义的数据结构合并(例如合并两个自定义字典)
  94. class CustomDict:
  95. def __init__(self, data):
  96. self.data = data
  97. def __or__(self, other):
  98. return CustomDict({**self.data, **other.data})
  99. def __repr__(self):
  100. return f"CustomDict({self.data})"
  101. if __name__ == '__main__':
  102. dict1 = CustomDict({"a": 1, "b": 2})
  103. dict2 = CustomDict({"b": 3, "c": 4})
  104. merged_dict = dict1 | dict2
  105. print(merged_dict) # 输出:CustomDict({'a': 1, 'b': 3, 'c': 4})
  106. # 11、版本控制合并(模拟两个软件版本的合并)
  107. class Version:
  108. def __init__(self, major, minor, patch):
  109. self.major = major
  110. self.minor = minor
  111. self.patch = patch
  112. def __or__(self, other):
  113. # 在这个例子中,我们简单地取两个版本中的最大值作为合并后的版本
  114. # 在实际的版本控制系统中,合并版本会更为复杂
  115. return Version(
  116. max(self.major, other.major),
  117. max(self.minor, other.minor),
  118. max(self.patch, other.patch)
  119. )
  120. def __repr__(self):
  121. return f"Version({self.major}.{self.minor}.{self.patch})"
  122. if __name__ == '__main__':
  123. v1 = Version(1, 2, 3)
  124. v2 = Version(1, 3, 1)
  125. merged_version = v1 | v2
  126. print(merged_version) # 输出:Version(1.3.3)
  127. # 12、图形路径合并(例如合并两个图形路径以创建复杂形状)
  128. class Path:
  129. def __init__(self, points):
  130. self.points = points
  131. def __or__(self, other):
  132. # 合并两个路径,简单地将它们的点连接起来(注意:这不会创建有效的图形路径)
  133. return Path(self.points + other.points)
  134. def __repr__(self):
  135. return f"Path({self.points})"
  136. if __name__ == '__main__':
  137. path1 = Path([(0, 0), (1, 1), (2, 0)])
  138. path2 = Path([(2, 0), (3, 1), (4, 0)])
  139. combined_path = path1 | path2
  140. print(combined_path) # 输出:Path([(0, 0), (1, 1), (2, 0), (2, 0), (3, 1), (4, 0)])

54、__pos__方法

54-1、语法
  1. __pos__(self, /)
  2. + self
54-2、参数

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

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

54-3、功能

        用于定义当对象被一元正号(+)运算符作用时的行为。

54-4、返回值

        返回一个对象,该对象代表了对原始对象应用一元正号运算符后的结果。

54-5、说明

       无

54-6、用法
  1. # 054、__pos__方法:
  2. # 1、简单数值类
  3. class Number:
  4. def __init__(self, value):
  5. self.value = value
  6. def __pos__(self):
  7. return Number(self.value) # 通常不会改变值,但为了演示
  8. def __repr__(self):
  9. return f"Number({self.value})"
  10. if __name__ == '__main__':
  11. n = Number(5)
  12. print(+n) # 输出: Number(5)
  13. # 2、复数类
  14. class ComplexNumber:
  15. def __init__(self, real, imag):
  16. self.real = real
  17. self.imag = imag
  18. def __pos__(self):
  19. return self # 复数取正还是它本身
  20. def __repr__(self):
  21. return f"ComplexNumber({self.real},{self.imag})"
  22. if __name__ == '__main__':
  23. cn = ComplexNumber(1, 2)
  24. print(+cn) # 输出: ComplexNumber(1,2)
  25. # 3、向量类
  26. class Vector2D:
  27. def __init__(self, x, y):
  28. self.x = x
  29. self.y = y
  30. def __pos__(self):
  31. return self # 向量取正还是它本身
  32. def __repr__(self):
  33. return f"Vector2D({self.x},{self.y})"
  34. if __name__ == '__main__':
  35. v = Vector2D(3, 4)
  36. print(+v) # 输出: Vector2D(3,4)
  37. # 4、温度类(摄氏度)
  38. class Temperature:
  39. def __init__(self, celsius):
  40. self.celsius = celsius
  41. def __pos__(self):
  42. return self # 温度取正还是它本身
  43. def __repr__(self):
  44. return f"{self.celsius}°C"
  45. if __name__ == '__main__':
  46. t = Temperature(25)
  47. print(+t) # 输出: 25°C
  48. # 5、自定义字符串类
  49. class CustomString:
  50. def __init__(self, s):
  51. self.s = s
  52. def __pos__(self):
  53. return self # 字符串取正还是它本身
  54. def __str__(self):
  55. return self.s
  56. if __name__ == '__main__':
  57. cs = CustomString("Myelsa")
  58. print(+cs) # 输出: Myelsa
  59. # 6、时间类
  60. from datetime import datetime
  61. class Time:
  62. def __init__(self, dt):
  63. self.dt = dt
  64. def __pos__(self):
  65. return self # 时间取正还是它本身
  66. def __repr__(self):
  67. return self.dt.strftime("%H:%M:%S")
  68. if __name__ == '__main__':
  69. t = Time(datetime.now())
  70. print(+t) # 输出当前时间,如: 16:59:58
  71. # 7、货币类
  72. class Money:
  73. def __init__(self, amount, currency):
  74. self.amount = amount
  75. self.currency = currency
  76. def __pos__(self):
  77. return self # 货币取正还是它本身
  78. def __repr__(self):
  79. return f"{self.amount} {self.currency}"
  80. if __name__ == '__main__':
  81. m = Money(100, "USD")
  82. print(+m) # 输出: 100 USD
  83. # 8、分数类
  84. from fractions import Fraction
  85. class FractionWrapper:
  86. def __init__(self, numerator, denominator):
  87. self.fraction = Fraction(numerator, denominator)
  88. def __pos__(self):
  89. return FractionWrapper(self.fraction.numerator, self.fraction.denominator) # 包装器取正还是它本身
  90. def __repr__(self):
  91. return str(self.fraction)
  92. if __name__ == '__main__':
  93. f = FractionWrapper(1, 2)
  94. print(+f) # 输出: 1/2
  95. # 9、矩阵类(2x2)
  96. class Matrix2x2:
  97. def __init__(self, a, b, c, d):
  98. self.a = a
  99. self.b = b
  100. self.c = c
  101. self.d = d
  102. def __pos__(self):
  103. return Matrix2x2(self.a, self.b, self.c, self.d) # 矩阵取正还是它本身
  104. def __repr__(self):
  105. return f"[[{self.a}, {self.b}], [{self.c}, {self.d}]]"
  106. if __name__ == '__main__':
  107. m = Matrix2x2(1, 2, 3, 4)
  108. print(+m) # 输出: [[1, 2], [3, 4]]
  109. # 10、有理数类
  110. class Rational:
  111. def __init__(self, numerator, denominator=1):
  112. self.numerator = numerator
  113. self.denominator = denominator if denominator != 0 else 1
  114. self.simplify()
  115. def simplify(self):
  116. # 这里省略了简化分数的逻辑
  117. pass
  118. def __pos__(self):
  119. return Rational(self.numerator, self.denominator) # 有理数取正还是它本身
  120. def __repr__(self):
  121. return f"{self.numerator}/{self.denominator}"
  122. if __name__ == '__main__':
  123. r = Rational(3, 2)
  124. print(+r) # 输出: 3/2
  125. # 11、坐标点类(三维)
  126. class Point3D:
  127. def __init__(self, x, y, z):
  128. self.x = x
  129. self.y = y
  130. self.z = z
  131. def __pos__(self):
  132. return Point3D(self.x, self.y, self.z) # 坐标点取正还是它本身
  133. def __repr__(self):
  134. return f"({self.x}, {self.y}, {self.z})"
  135. if __name__ == '__main__':
  136. p = Point3D(1, 2, 3)
  137. print(+p) # 输出: (1, 2, 3)
  138. # 12、四元数类
  139. class Quaternion:
  140. def __init__(self, w, x, y, z):
  141. self.w = w
  142. self.x = x
  143. self.y = y
  144. self.z = z
  145. def __pos__(self):
  146. return Quaternion(self.w, self.x, self.y, self.z) # 四元数取正还是它本身
  147. def __repr__(self):
  148. return f"({self.w}, {self.x}, {self.y}, {self.z})"
  149. if __name__ == '__main__':
  150. q = Quaternion(1, 0, 0, 0)
  151. print(+q) # 输出: (1, 0, 0, 0)

55、__pow__方法

55-1、语法
  1. __pow__(self, other, mod=None, /)
  2. Return pow(self, other, mod)
55-2、参数

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

55-2-2、 other(必须):表示要用于幂运算的指数。

55-2-3、mod(可选):如果提供了这个参数,则执行模幂运算。

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

55-3、功能

        用于定义对象之间的幂运算(**)以及模幂运算(pow(x, y, z))。

55-4、返回值

        返回一个对象,该对象代表了对self对象应用幂运算(或模幂运算)后的结果。

55-5、说明

        在pow(x, y, z)中, x是self,y是other,而z是mod。如果不提供mod(即mod=None),则执行普通的幂运算。

55-6、用法
  1. # 055、__pow__方法:
  2. # 1、简单数值类
  3. class SimpleNumber:
  4. def __init__(self, value):
  5. self.value = value
  6. def __pow__(self, other, mod=None):
  7. if mod is None:
  8. return SimpleNumber(self.value ** other)
  9. return SimpleNumber(pow(self.value, other, mod))
  10. def __repr__(self):
  11. return f"SimpleNumber({self.value})"
  12. if __name__ == '__main__':
  13. num = SimpleNumber(2)
  14. print(num ** 3) # 输出: SimpleNumber(8)
  15. print(num.__pow__(10, 7)) # 输出: SimpleNumber(2),直接调用__pow__方法并传入模数
  16. # 2、矩阵类(2x2)
  17. import numpy as np
  18. class Matrix2x2:
  19. def __init__(self, data):
  20. self.data = np.array(data, dtype=float).reshape(2, 2)
  21. def __pow__(self, other, mod=None):
  22. if mod is not None:
  23. raise NotImplementedError("Modulo not supported for matrices")
  24. return Matrix2x2(np.linalg.matrix_power(self.data, other))
  25. def __repr__(self):
  26. return f"Matrix2x2(\n{self.data}\n)"
  27. if __name__ == '__main__':
  28. m = Matrix2x2([[1, 2], [3, 4]])
  29. print(m ** 2) # 输出矩阵的平方
  30. # 3、时间单位的幂运算
  31. class TimeUnit:
  32. def __init__(self, seconds):
  33. self.seconds = seconds
  34. def __pow__(self, other, mod=None):
  35. # 时间单位取幂在物理上没有意义,但这里假设表示时间间隔的重复
  36. return TimeUnit(self.seconds * other)
  37. def __repr__(self):
  38. return f"TimeUnit({self.seconds} seconds)"
  39. if __name__ == '__main__':
  40. time = TimeUnit(60) # 1分钟
  41. print(time ** 3) # 输出: TimeUnit(180 seconds),即3分钟
  42. # 4、自定义单位类(如米的n次方)
  43. class UnitMeter:
  44. def __init__(self, value):
  45. self.value = value
  46. def __pow__(self, other, mod=None):
  47. # 米的n次方在物理上可能表示体积、面积等
  48. return UnitMeterPower(self.value, other)
  49. def __repr__(self):
  50. return f"UnitMeter({self.value} m)"
  51. class UnitMeterPower:
  52. def __init__(self, base_value, exponent):
  53. self.base_value = base_value
  54. self.exponent = exponent
  55. def __repr__(self):
  56. return f"UnitMeter^{self.exponent}({self.base_value} m)"
  57. if __name__ == '__main__':
  58. meter = UnitMeter(1)
  59. print(meter ** 3) # 输出: UnitMeter^3(1 m)
  60. # 5、复数类
  61. class ComplexNumber:
  62. def __init__(self, real, imag):
  63. self.real = real
  64. self.imag = imag
  65. def __pow__(self, other):
  66. # 假设other是实数或另一个复数
  67. # 这里简化处理,只处理实数幂
  68. if isinstance(other, int) or isinstance(other, float):
  69. magnitude = (self.real ** 2 + self.imag ** 2) ** (other / 2)
  70. angle = (other * math.atan2(self.imag, self.real)) % (2 * math.pi)
  71. return ComplexNumber(magnitude * math.cos(angle), magnitude * math.sin(angle))
  72. else:
  73. raise TypeError("Power must be a real number.")
  74. def __repr__(self):
  75. return f"ComplexNumber({self.real}+{self.imag}j)"
  76. if __name__ == '__main__':
  77. import math
  78. c = ComplexNumber(1, 1)
  79. print(c ** 2) # 输出:ComplexNumber(1.2246467991473532e-16+2.0j)
  80. # 6、坐标点类(二维空间)
  81. class Point2D:
  82. def __init__(self, x, y):
  83. self.x = x
  84. self.y = y
  85. def __pow__(self, other):
  86. # 这里的幂运算被重新定义为距离的平方(欧氏距离)
  87. return self.x ** 2 + self.y ** 2
  88. def __repr__(self):
  89. return f"Point2D({self.x},{self.y})"
  90. if __name__ == '__main__':
  91. p = Point2D(3, 4)
  92. print(p ** 2) # 输出: 25,表示点(3,4)到原点的距离的平方
  93. # 7、图形变换类(缩放)
  94. class ScaleTransform:
  95. def __init__(self, scale_factor):
  96. self.scale_factor = scale_factor
  97. def __pow__(self, other):
  98. # 幂运算表示连续的缩放
  99. return ScaleTransform(self.scale_factor ** other)
  100. def apply_to(self, point):
  101. # 假设point有x和y属性
  102. return Point2D(point.x * self.scale_factor, point.y * self.scale_factor)
  103. def __repr__(self):
  104. return f"ScaleTransform({self.scale_factor})"
  105. if __name__ == '__main__':
  106. scale = ScaleTransform(2)
  107. print(scale ** 3) # 输出: ScaleTransform(8),表示连续三次放大2倍
  108. # 8、自定义向量类
  109. class Vector:
  110. def __init__(self, *components):
  111. self.components = components
  112. def __pow__(self, other):
  113. # 假设other是整数,表示向量的点积自乘
  114. if isinstance(other, int):
  115. return Vector(*[comp ** other for comp in self.components])
  116. else:
  117. raise TypeError("Power must be an integer.")
  118. def __repr__(self):
  119. return f"Vector({', '.join(map(str, self.components))})"
  120. if __name__ == '__main__':
  121. v = Vector(1, 2, 3)
  122. print(v ** 2) # 输出: Vector(1, 4, 9),表示每个分量都平方了

五、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、博客个人主页

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

/ 登录

评论记录:

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

分类栏目

后端 (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