首页 最新 热门 推荐

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

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

  • 25-03-03 05:09
  • 2311
  • 13813
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、避免过度使用

四、魔法方法

74、__subclasses__方法

74-1、语法

74-2、参数

74-3、功能

74-4、返回值

74-5、说明

74-6、用法

75、__truediv__方法

75-1、语法

75-2、参数

75-3、功能

75-4、返回值

75-5、说明

75-6、用法

76、__trunc__方法

76-1、语法

76-2、参数

76-3、功能

76-4、返回值

76-5、说明

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

四、魔法方法

74、__subclasses__方法

74-1、语法
  1. __subclasses__(self, /)
  2. Return a list of immediate subclasses
74-2、参数

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

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

74-3、功能

        检索并返回一个包含给定类(即self)所有直接子类的列表。

74-4、返回值

       返回一个列表,列表中的元素是给定类的直接子类类型对象。

74-5、说明

        如果没有任何子类,那么返回的列表将是空的。

74-6、用法
  1. # 074、__subclasses__方法:
  2. # 1、游戏角色类
  3. class Character:
  4. pass
  5. class Warrior(Character):
  6. pass
  7. class Mage(Character):
  8. pass
  9. print(Character.__subclasses__()) # 输出:[, ]
  10. # 2、动物分类
  11. class Animal:
  12. pass
  13. class Mammal(Animal):
  14. pass
  15. class Bird(Animal):
  16. pass
  17. print(Animal.__subclasses__()) # 输出:[, ]
  18. # 3、数据库模型
  19. class BaseModel:
  20. pass
  21. class User(BaseModel):
  22. pass
  23. class Product(BaseModel):
  24. pass
  25. print(BaseModel.__subclasses__()) # 输出:[, ]
  26. # 4、图形绘制
  27. class Shape:
  28. pass
  29. class Circle(Shape):
  30. pass
  31. class Rectangle(Shape):
  32. pass
  33. print(Shape.__subclasses__()) # 输出:[, ]
  34. # 5、汽车类型
  35. class Car:
  36. pass
  37. class ElectricCar(Car):
  38. pass
  39. class GasolineCar(Car):
  40. pass
  41. print(Car.__subclasses__()) # 输出:[, ]
  42. # 6、支付方式
  43. class PaymentMethod:
  44. pass
  45. class CreditCard(PaymentMethod):
  46. pass
  47. class DebitCard(PaymentMethod):
  48. pass
  49. print(PaymentMethod.__subclasses__()) # 输出:[, ]
  50. # 7、文件系统
  51. class FileSystemObject:
  52. pass
  53. class File(FileSystemObject):
  54. pass
  55. class Directory(FileSystemObject):
  56. pass
  57. print(FileSystemObject.__subclasses__()) # 输出:[, ]
  58. # 8、数学运算
  59. class MathOperation:
  60. pass
  61. class Addition(MathOperation):
  62. pass
  63. class Subtraction(MathOperation):
  64. pass
  65. print(MathOperation.__subclasses__()) # 输出:[, ]
  66. # 9、用户权限
  67. class Permission:
  68. pass
  69. class ReadPermission(Permission):
  70. pass
  71. class WritePermission(Permission):
  72. pass
  73. print(Permission.__subclasses__()) # 输出:[, ]
  74. # 10、食物分类
  75. class Food:
  76. pass
  77. class Fruit(Food):
  78. pass
  79. class Vegetable(Food):
  80. pass
  81. print(Food.__subclasses__()) # 输出:[, ]
  82. # 11、颜色分类
  83. class Color:
  84. pass
  85. class PrimaryColor(Color):
  86. pass
  87. class SecondaryColor(Color):
  88. pass
  89. print(Color.__subclasses__()) # 输出:[, ]
  90. # 12、网络协议
  91. class Protocol:
  92. pass
  93. class TCP(Protocol):
  94. pass
  95. class UDP(Protocol):
  96. pass
  97. print(Protocol.__subclasses__()) # 输出:[, ]

75、__truediv__方法

75-1、语法
  1. __truediv__(self, other, /)
  2. Return self / other
75-2、参数

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

75-2-2、other(必须):表示除法操作的第二个操作数。当你写a / b时,a是self,而b是other。

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

75-3、功能

        用于定义对象之间的除法操作的行为。

75-4、返回值

        返回一个表示除法结果的对象。这个对象可以是任何类型,但通常它会返回与调用该方法的对象相同类型的结果,以保持类型的一致性。

75-5、说明

        无

75-6、用法
  1. # 075、__truediv__方法:
  2. # 1、分数四则运算
  3. from fractions import Fraction
  4. class MyFraction:
  5. def __init__(self, numerator, denominator=1):
  6. # 确保分母不为0
  7. if denominator == 0:
  8. raise ValueError("Denominator cannot be zero")
  9. # 使用内置的Fraction类进行分数的创建和化简
  10. self.fraction = Fraction(numerator, denominator)
  11. def __str__(self):
  12. # 返回分数的字符串表示
  13. return str(self.fraction)
  14. def __add__(self, other):
  15. # 加法运算
  16. if isinstance(other, MyFraction):
  17. return MyFraction(self.fraction + other.fraction)
  18. elif isinstance(other, (int, float)):
  19. # 假设整数或浮点数与分数相加时,整数或浮点数作为分数的分子
  20. return MyFraction(self.fraction + Fraction(other))
  21. else:
  22. raise TypeError("Unsupported operand types for +: 'MyFraction' and '{}'".format(type(other).__name__))
  23. def __sub__(self, other):
  24. # 减法运算
  25. if isinstance(other, MyFraction):
  26. return MyFraction(self.fraction - other.fraction)
  27. elif isinstance(other, (int, float)):
  28. return MyFraction(self.fraction - Fraction(other))
  29. else:
  30. raise TypeError("Unsupported operand types for -: 'MyFraction' and '{}'".format(type(other).__name__))
  31. def __mul__(self, other):
  32. # 乘法运算
  33. if isinstance(other, MyFraction):
  34. return MyFraction(self.fraction * other.fraction)
  35. elif isinstance(other, (int, float)):
  36. return MyFraction(self.fraction * Fraction(other))
  37. else:
  38. raise TypeError("Unsupported operand types for *: 'MyFraction' and '{}'".format(type(other).__name__))
  39. def __truediv__(self, other):
  40. # 除法运算
  41. if isinstance(other, MyFraction):
  42. return MyFraction(self.fraction / other.fraction)
  43. elif isinstance(other, (int, float)):
  44. return MyFraction(self.fraction / Fraction(other))
  45. else:
  46. raise TypeError("Unsupported operand types for /: 'MyFraction' and '{}'".format(type(other).__name__))
  47. if __name__ == '__main__':
  48. f1 = MyFraction(1, 2) # 1/2
  49. f2 = MyFraction(2, 3) # 2/3
  50. f3 = f1 + f2 # 1/2 + 2/3 = 7/6
  51. f4 = f1 - f2 # 1/2 - 2/3 = -1/6
  52. f5 = f1 * f2 # 1/2 * 2/3 = 1/3
  53. f6 = f1 / f2 # 1/2 / 2/3 = 3/4
  54. print(f"f1 + f2 = {f3}")
  55. print(f"f1 - f2 = {f4}")
  56. print(f"f1 * f2 = {f5}")
  57. print(f"f1 / f2 = {f6}")
  58. # f1 + f2 = 7/6
  59. # f1 - f2 = -1/6
  60. # f1 * f2 = 1/3
  61. # f1 / f2 = 3/4
  62. # 2、矩阵类(实现两个矩阵之间的除法,通常这指的是矩阵的逆或矩阵与向量的除法)
  63. import numpy as np
  64. class Matrix:
  65. def __init__(self, data):
  66. self.data = np.array(data)
  67. def __truediv__(self, other):
  68. # 这里为了简化,我们只实现矩阵与向量的除法(即解线性方程组)
  69. if isinstance(other, Matrix) and other.data.ndim == 1:
  70. # 使用numpy的linalg.solve方法解线性方程组
  71. return Matrix(np.linalg.solve(self.data, other.data))
  72. else:
  73. raise TypeError("Unsupported operand types for /: 'Matrix' and '{}'".format(type(other).__name__))
  74. def __str__(self):
  75. return str(self.data)
  76. if __name__ == '__main__':
  77. A = Matrix([[1, 2], [3, 4]])
  78. b = Matrix([1, 2])
  79. x = A / b # 解线性方程组 Ax = b
  80. print(x) # 输出解向量x
  81. # 3、时间类(实现两个时间间隔之间的除法)
  82. from datetime import timedelta
  83. class TimeInterval:
  84. def __init__(self, days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0):
  85. self.delta = timedelta(days=days, seconds=seconds, microseconds=microseconds, milliseconds=milliseconds,
  86. minutes=minutes, hours=hours, weeks=weeks)
  87. def __truediv__(self, other):
  88. # 假设other是一个整数,表示要将时间间隔分割的份数
  89. if isinstance(other, int):
  90. # 使用timedelta的total_seconds方法计算总秒数,然后均分
  91. total_seconds = self.delta.total_seconds()
  92. seconds_per_interval = total_seconds / other
  93. return TimeInterval(seconds=int(seconds_per_interval))
  94. else:
  95. raise TypeError("Unsupported operand types for /: 'TimeInterval' and '{}'".format(type(other).__name__))
  96. def __str__(self):
  97. return str(self.delta)
  98. if __name__ == '__main__':
  99. interval = TimeInterval(hours=2)
  100. result = interval / 4 # 将2小时均分为4份
  101. print(result) # 输出类似 0:30:00 的结果,表示每份是30分钟
  102. # 4、分数类(实现两个分数之间的除法)
  103. from fractions import Fraction
  104. class MyFraction:
  105. def __init__(self, numerator, denominator):
  106. self.numerator = numerator
  107. self.denominator = denominator
  108. def __truediv__(self, other):
  109. # 假设other也是一个MyFraction的实例
  110. if isinstance(other, MyFraction):
  111. # 分数除法的规则:a/b ÷ c/d = a/b × d/c
  112. return MyFraction(self.numerator * other.denominator, self.denominator * other.numerator)
  113. elif isinstance(other, (int, float)):
  114. # 分数除以整数或浮点数,可以看作分数乘以整数的倒数或浮点数的倒数
  115. return MyFraction(self.numerator, self.denominator * other)
  116. else:
  117. raise TypeError("Unsupported operand types for /: 'MyFraction' and '{}'".format(type(other).__name__))
  118. def __str__(self):
  119. return f"{self.numerator}/{self.denominator}"
  120. if __name__ == '__main__':
  121. f1 = MyFraction(1, 2)
  122. f2 = MyFraction(2, 3)
  123. result = f1 / f2
  124. print(result) # 输出:3/4
  125. # 5、图形类(例如,二维图形的面积“除法”)
  126. class Rectangle:
  127. def __init__(self, width, height):
  128. self.width = width
  129. self.height = height
  130. def area(self):
  131. return self.width * self.height
  132. def __truediv__(self, other_area):
  133. # 这里假设other_area是一个数值,表示要均分的面积
  134. # 返回一个Rectangle对象,其面积尽可能接近给定值,但宽度和高度可能不是整数
  135. return Rectangle(self.width * (self.area() / other_area) ** 0.5,
  136. self.height * (self.area() / other_area) ** 0.5)
  137. if __name__ == '__main__':
  138. rect = Rectangle(4, 6)
  139. small_rect = rect / 10 # 尝试将矩形面积均分为10份,但结果可能不是完美的矩形
  140. print(small_rect.width, small_rect.height) # 输出:类似于6.196773353931867 9.2951600308978
  141. # 6、文本处理类(例如,字符串按长度“除法”)
  142. class TextChunk:
  143. def __init__(self, text):
  144. self.text = text
  145. def __truediv__(self, chunk_size):
  146. # 这里不是真正的除法,而是将文本按指定大小分割
  147. chunks = [self.text[i:i + chunk_size] for i in range(0, len(self.text), chunk_size)]
  148. return chunks
  149. if __name__ == '__main__':
  150. text = TextChunk("Hello, world! This is a test.")
  151. chunks = text / 5 # 将文本每5个字符分割一次
  152. for chunk in chunks:
  153. print(chunk)
  154. # 7、自定义数值类型(例如,有理数)
  155. class Rational:
  156. def __init__(self, numerator, denominator):
  157. self.numerator = numerator
  158. self.denominator = denominator
  159. def __truediv__(self, other):
  160. if isinstance(other, Rational):
  161. return Rational(self.numerator * other.denominator, self.denominator * other.numerator)
  162. elif isinstance(other, int) or isinstance(other, float):
  163. return Rational(self.numerator, self.denominator * other)
  164. def __str__(self):
  165. return f"{self.numerator}/{self.denominator}"
  166. if __name__ == '__main__':
  167. r1 = Rational(1, 2)
  168. r2 = Rational(1, 3)
  169. result = r1 / r2
  170. print(result) # 输出:3/2
  171. # 8、颜色类(支持颜色的“混合”或“亮度调整”)
  172. class Color:
  173. def __init__(self, r, g, b):
  174. self.r = r
  175. self.g = g
  176. self.b = b
  177. def __truediv__(self, factor):
  178. # 假设factor是一个介于0和1之间的浮点数,用于调整颜色的亮度
  179. return Color(int(self.r / factor), int(self.g / factor), int(self.b / factor))
  180. if __name__ == '__main__':
  181. color = Color(128, 255, 0)
  182. darker_color = color / 2 # 假设这里的意思是降低亮度,而不是真的除法
  183. print(darker_color.r, darker_color.g, darker_color.b) # 输出类似 64 127 0 的颜色值
  184. # 9、复数类
  185. class Complex:
  186. def __init__(self, real, imag):
  187. self.real = real
  188. self.imag = imag
  189. def __truediv__(self, other):
  190. if isinstance(other, Complex):
  191. denominator = other.real ** 2 + other.imag ** 2
  192. return Complex((self.real * other.real + self.imag * other.imag) / denominator,
  193. (self.imag * other.real - self.real * other.imag) / denominator)
  194. else:
  195. return Complex(self.real / other, self.imag / other)
  196. if __name__ == '__main__':
  197. c1 = Complex(1, 2)
  198. c2 = c1 / 2
  199. print(c2.real, c2.imag) # 输出 0.5 1.0
  200. # 10、向量类(点乘)
  201. class Vector:
  202. def __init__(self, x, y):
  203. self.x = x
  204. self.y = y
  205. def __truediv__(self, scalar):
  206. return Vector(self.x / scalar, self.y / scalar)
  207. if __name__ == '__main__':
  208. v = Vector(2, 4)
  209. result = v / 2
  210. print(result.x, result.y) # 输出 1.0 2.0

76、__trunc__方法

76-1、语法
  1. __trunc__(self, /)
  2. Truncating an Integral returns itself
76-2、参数

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

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

76-3、功能

        用于定义当对象被int()函数调用时应该返回什么值。

76-4、返回值

        返回一个整数,表示对象被截断后的值。

76-5、说明

        该方法通常用于实现那些可以被截断为整数的对象,比如浮点数或自定义的数字类型。

76-6、用法
  1. # 076、__trunc__方法:
  2. # 1、分数类
  3. class Fraction:
  4. def __init__(self, numerator, denominator):
  5. self.numerator = numerator
  6. self.denominator = denominator
  7. def __trunc__(self):
  8. return self.numerator // (self.denominator or 1)
  9. if __name__ == '__main__':
  10. f = Fraction(7, 3)
  11. print(int(f)) # 输出: 2,因为7/3的整数部分是2
  12. # 2、自定义浮点数类(四舍五入到最接近的整数)
  13. class RoundedFloat:
  14. def __init__(self, value):
  15. self.value = round(value)
  16. def __trunc__(self):
  17. return int(self.value)
  18. if __name__ == '__main__':
  19. rf = RoundedFloat(3.7)
  20. print(int(rf)) # 输出: 4
  21. # 3、时间戳类(只取小时部分)
  22. from datetime import datetime, timedelta
  23. class Timestamp:
  24. def __init__(self, dt):
  25. self.dt = dt
  26. def __trunc__(self):
  27. return (self.dt - timedelta(minutes=self.dt.minute, seconds=self.dt.second,
  28. microseconds=self.dt.microsecond)).replace(tzinfo=None)
  29. if __name__ == '__main__':
  30. ts = Timestamp(datetime.now())
  31. print(ts.__trunc__().strftime("%Y-%m-%d %H:%M:%S")) # 输出:类似于2024-06-08 13:00:00
  32. # 4、字符串长度类
  33. class StringLength:
  34. def __init__(self, string):
  35. self.string = string
  36. def __trunc__(self):
  37. return len(self.string)
  38. if __name__ == '__main__':
  39. length = StringLength("Hello, World!")
  40. print(int(length)) # 输出: 13
  41. # 5、自定义颜色类(亮度截断)
  42. class Color:
  43. def __init__(self, r, g, b):
  44. self.r = r
  45. self.g = g
  46. self.b = b
  47. def brightness(self):
  48. return (self.r + self.g + self.b) // 3
  49. def __trunc__(self):
  50. return int(self.brightness())
  51. if __name__ == '__main__':
  52. color = Color(255, 128, 0)
  53. print(int(color)) # 输出: 127
  54. # 6、自定义向量类(长度截断)
  55. import math
  56. class Vector:
  57. def __init__(self, x, y):
  58. self.x = x
  59. self.y = y
  60. def length(self):
  61. return math.sqrt(self.x ** 2 + self.y ** 2)
  62. def __trunc__(self):
  63. return int(round(self.length()))
  64. if __name__ == '__main__':
  65. vector = Vector(3, 4)
  66. print(int(vector)) # 输出: 5 (向量的长度,四舍五入到最接近的整数)
  67. # 7、自定义货币类
  68. class Money:
  69. def __init__(self, amount, currency='USD'):
  70. self.amount = amount
  71. self.currency = currency
  72. def __trunc__(self):
  73. return int(self.amount)
  74. if __name__ == '__main__':
  75. money = Money(123.45)
  76. print(int(money)) # 输出: 123 (忽略小数部分)
  77. # 8、自定义价格范围类
  78. class PriceRange:
  79. def __init__(self, min_price, max_price):
  80. self.min_price = min_price
  81. self.max_price = max_price
  82. def midpoint(self):
  83. return (self.min_price + self.max_price) / 2
  84. def __trunc__(self):
  85. return int(round(self.midpoint()))
  86. if __name__ == '__main__':
  87. price_range = PriceRange(10, 20)
  88. print(int(price_range)) # 输出: 15 (价格范围的中点,四舍五入到最接近的整数)
  89. # 9、自定义进度条类
  90. class ProgressBar:
  91. def __init__(self, total, current=0):
  92. self.total = total
  93. self.current = current
  94. def __str__(self):
  95. # 这里只是简单示意,实际上可能需要更复杂的逻辑来显示进度条
  96. return f"[{'#' * (self.current // (self.total // 10))} {' ' * ((self.total // 10) - (self.current // (self.total // 10)))}] {self.current}/{self.total}"
  97. def __trunc__(self):
  98. # 假设进度条当前进度可以“截断”为完成的百分比(整数)
  99. return int((self.current / self.total) * 100)
  100. if __name__ == '__main__':
  101. progress = ProgressBar(100, 68)
  102. print(progress) # 输出类似: [###### ] 68/100
  103. print(int(progress)) # 输出: 68(假设我们想要的是百分比,但这里仅作为示例)
  104. # 10、自定义评分系统类
  105. class RatingSystem:
  106. def __init__(self, score):
  107. self.score = score
  108. def __trunc__(self):
  109. # 假设评分可以“截断”为整数星级(去掉小数部分)
  110. return int(self.score)
  111. if __name__ == '__main__':
  112. rating = RatingSystem(4.7)
  113. print(int(rating)) # 输出: 4(四星级评价)
  114. # 11、自定义日期范围类
  115. from datetime import date
  116. class DateRange:
  117. def __init__(self, start_date, end_date):
  118. self.start_date = start_date
  119. self.end_date = end_date
  120. def __trunc__(self):
  121. # 假设我们想要得到日期范围中天数的整数部分(不考虑具体的日期)
  122. return (self.end_date - self.start_date).days
  123. if __name__ == '__main__':
  124. date_range = DateRange(date(2019, 3, 13), date(2024, 6, 8))
  125. print(int(date_range)) # 输出: 1914(日期范围中的天数)
  126. # 12、自定义物品清单类(库存量截断)
  127. class InventoryItem:
  128. def __init__(self, name, quantity):
  129. self.name = name
  130. self.quantity = quantity
  131. def __trunc__(self):
  132. # 假设我们想要获取库存量的整数部分(不考虑小数,可能是用于某些只能存储整数数量的情况)
  133. return int(self.quantity)
  134. if __name__ == '__main__':
  135. item = InventoryItem("Apple", 10.5) # 假设有10个半苹果是不合理的,所以我们截断为10个
  136. print(int(item)) # 输出: 10(库存量)

五、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、博客个人主页

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

/ 登录

评论记录:

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

分类栏目

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