首页 最新 热门 推荐

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

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

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

四、魔法方法

41、__xor__方法

41-1、语法

41-2、参数

41-3、功能

41-4、返回值

41-5、说明

41-6、用法

42、__le__方法

42-1、语法

42-2、参数

42-3、功能

42-4、返回值

42-5、说明

42-6、用法

43、__len__方法

43-1、语法

43-2、参数

43-3、功能

43-4、返回值

43-5、说明

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

四、魔法方法

41、__xor__方法

41-1、语法
  1. __xor__(self, other, /)
  2. Return self ^ other
41-2、参数

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

41-2-2、 other(必须):表示要与self进行异或运算的第二个对象,即__xor__ 法操作的右侧操作数。

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

41-3、功能

        用于实现自定义类型的异或(XOR)运算操作。

41-4、返回值

        返回一个与self和other进行异或运算后的结果。

41-5、说明

        无

41-6、用法
  1. # 041、__xor__方法:
  2. # 1、基本整数异或
  3. class MyInt:
  4. def __init__(self, value):
  5. self.value = value
  6. def __xor__(self, other):
  7. if not isinstance(other, MyInt):
  8. raise TypeError("Unsupported operand type(s) for ^: 'MyInt' and '{}'".format(type(other).__name__))
  9. return MyInt(self.value ^ other.value)
  10. def __repr__(self):
  11. return f"MyInt({self.value})"
  12. if __name__ == '__main__':
  13. a = MyInt(5)
  14. b = MyInt(3)
  15. print(a ^ b) # 输出: MyInt(6)
  16. # 2、字符串异或(假设为二进制字符串)
  17. class BinaryString:
  18. def __init__(self, value):
  19. if not all(c in '01' for c in value):
  20. raise ValueError("Value must contain only '0' and '1'.")
  21. self.value = value
  22. def __xor__(self, other):
  23. if not isinstance(other, BinaryString):
  24. raise TypeError("Unsupported operand type(s) for ^: 'BinaryString' and '{}'".format(type(other).__name__))
  25. if len(self.value) != len(other.value):
  26. raise ValueError("Strings must have the same length.")
  27. return BinaryString(''.join('1' if a != b else '0' for a, b in zip(self.value, other.value)))
  28. def __repr__(self):
  29. return f"BinaryString('{self.value}')"
  30. if __name__ == '__main__':
  31. a = BinaryString('1010')
  32. b = BinaryString('1100')
  33. print(a ^ b) # 输出: BinaryString('0110')
  34. # 3、列表异或(元素比较)
  35. class ListXOR:
  36. def __init__(self, value):
  37. self.value = value
  38. def __xor__(self, other):
  39. if not isinstance(other, ListXOR):
  40. raise TypeError("Unsupported operand type(s) for ^: 'ListXOR' and '{}'".format(type(other).__name__))
  41. return ListXOR(
  42. [x for x in self.value if x not in other.value] + [x for x in other.value if x not in self.value])
  43. def __repr__(self):
  44. return f"ListXOR({self.value})"
  45. if __name__ == '__main__':
  46. a = ListXOR([1, 2, 3])
  47. b = ListXOR([2, 3, 4])
  48. print(a ^ b) # 输出: ListXOR([1, 4])
  49. # 4、自定义向量类异或
  50. class Vector:
  51. def __init__(self, x, y):
  52. self.x = x
  53. self.y = y
  54. def __xor__(self, other):
  55. if not isinstance(other, Vector):
  56. raise TypeError("Unsupported operand type(s) for ^: 'Vector' and '{}'".format(type(other).__name__))
  57. # 假设这里我们返回两个向量对应分量的差的绝对值
  58. return Vector(abs(self.x - other.x), abs(self.y - other.y))
  59. def __repr__(self):
  60. return f"Vector({self.x}, {self.y})"
  61. if __name__ == '__main__':
  62. a = Vector(1, 2)
  63. b = Vector(3, 1)
  64. print(a ^ b) # 输出: Vector(2, 1)
  65. # 5、自定义状态机异或(表示状态切换)
  66. class State:
  67. def __init__(self, name):
  68. self.name = name
  69. def __xor__(self, other):
  70. if not isinstance(other, State):
  71. raise TypeError("Unsupported operand type(s) for ^: 'State' and '{}'".format(type(other).__name__))
  72. # 假设这里我们有一个固定的状态切换逻辑
  73. if self.name == 'A' and other.name == 'B':
  74. return State('C')
  75. elif self.name == 'B' and other.name == 'A':
  76. return State('D')
  77. # ... 其他情况可以添加更多逻辑
  78. raise ValueError("Invalid state transition")
  79. def __repr__(self):
  80. return f"State({self.name})"
  81. if __name__ == '__main__':
  82. a = State('A')
  83. b = State('B')
  84. print(a ^ b) # 输出: State(C)
  85. # 6、自定义权限类异或(表示权限的合并或排除)
  86. class Permission:
  87. def __init__(self, name, value):
  88. self.name = name
  89. self.value = value
  90. def __xor__(self, other):
  91. if not isinstance(other, Permission):
  92. raise TypeError("Unsupported operand type(s) for ^: 'Permission' and '{}'".format(type(other).__name__))
  93. # 假设这里的异或操作是返回两个权限值的按位异或
  94. return Permission(self.name + '^' + other.name, self.value ^ other.value)
  95. def __repr__(self):
  96. return f"Permission({self.name}, {self.value})"
  97. if __name__ == '__main__':
  98. read = Permission('READ', 1)
  99. write = Permission('WRITE', 2)
  100. print(read ^ write) # 输出可能是 Permission(READ^WRITE, 3),但具体取决于value的类型和表示
  101. # 7、自定义集合类异或(表示集合的对称差集)
  102. class CustomSet:
  103. def __init__(self, elements=None):
  104. if elements is None:
  105. self.elements = set()
  106. else:
  107. self.elements = set(elements)
  108. def __xor__(self, other):
  109. if not isinstance(other, CustomSet):
  110. raise TypeError("Unsupported operand type(s) for ^: 'CustomSet' and '{}'".format(type(other).__name__))
  111. # 返回两个集合的对称差集
  112. return CustomSet(self.elements ^ other.elements)
  113. def __repr__(self):
  114. return f"CustomSet({self.elements})"
  115. if __name__ == '__main__':
  116. set1 = CustomSet([1, 2, 3])
  117. set2 = CustomSet([2, 3, 4])
  118. print(set1 ^ set2) # 输出: CustomSet({1, 4})
  119. # 8、自定义整数范围类异或(表示两个整数范围的重叠部分)
  120. class Range:
  121. def __init__(self, start, end):
  122. self.start = start
  123. self.end = end
  124. def __xor__(self, other):
  125. if not isinstance(other, Range):
  126. raise TypeError("Unsupported operand type(s) for ^: 'Range' and '{}'".format(type(other).__name__))
  127. # 这里的异或操作表示返回两个范围不重叠的部分,可能需要更复杂的逻辑来处理各种边界情况
  128. # 这里只提供一个简化的示例
  129. if self.start > other.end or self.end < other.start:
  130. # 没有重叠,返回两个范围本身
  131. return [self, other]
  132. else:
  133. # 有重叠,需要更复杂的逻辑来处理
  134. # 这里简化为只返回第一个范围(仅为示例)
  135. return [self]
  136. def __repr__(self):
  137. return f"Range({self.start}, {self.end})"
  138. if __name__ == '__main__':
  139. range1 = Range(3, 6)
  140. range2 = Range(5, 11)
  141. print(range1 ^ range2) # 输出: [Range(3, 6)]

42、__le__方法

42-1、语法
  1. __le__(self, other, /)
  2. Return self <= other
42-2、参数

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

42-2-2、 other(必须):与self进行比较的另一个对象。

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

42-3、功能

        用于定义对象之间的“小于或等于”比较操作。

42-4、返回值

        返回一个布尔值(True或False),表示self是否小于或等于other。

42-5、说明

        当你使用<=运算符时,other就是运算符右边的对象。

42-6、用法
  1. # 042、__le__方法:
  2. # 1、整数比较
  3. class MyInt:
  4. def __init__(self, value):
  5. self.value = value
  6. def __le__(self, other):
  7. if isinstance(other, MyInt):
  8. return self.value <= other.value
  9. elif isinstance(other, int):
  10. return self.value <= other
  11. else:
  12. return NotImplemented
  13. if __name__ == '__main__':
  14. a = MyInt(5)
  15. b = MyInt(10)
  16. print(a <= b) # True
  17. print(a <= 5) # True
  18. # 2、字符串长度比较
  19. class MyString:
  20. def __init__(self, value):
  21. self.value = value
  22. def __len__(self):
  23. return len(self.value)
  24. def __le__(self, other):
  25. if isinstance(other, MyString):
  26. return len(self) <= len(other)
  27. elif isinstance(other, (str, int)):
  28. return len(self.value) <= len(str(other))
  29. else:
  30. return NotImplemented
  31. if __name__ == '__main__':
  32. s1 = MyString("hello")
  33. s2 = MyString("world")
  34. print(s1 <= s2) # True
  35. print(s1 <= "hi") # False
  36. # 3、分数比较
  37. from fractions import Fraction
  38. class MyFraction:
  39. def __init__(self, numerator, denominator):
  40. self.value = Fraction(numerator, denominator)
  41. def __le__(self, other):
  42. if isinstance(other, MyFraction):
  43. return self.value <= other.value
  44. elif isinstance(other, (Fraction, int, float)):
  45. return self.value <= Fraction(other)
  46. else:
  47. return NotImplemented
  48. if __name__ == '__main__':
  49. f1 = MyFraction(1, 2)
  50. f2 = MyFraction(3, 4)
  51. print(f1 <= f2) # True
  52. print(f1 <= 0.5) # True
  53. # 4、日期比较
  54. from datetime import date
  55. class MyDate:
  56. def __init__(self, year, month, day):
  57. self.value = date(year, month, day)
  58. def __le__(self, other):
  59. if isinstance(other, MyDate):
  60. return self.value <= other.value
  61. elif isinstance(other, date):
  62. return self.value <= other
  63. else:
  64. return NotImplemented
  65. if __name__ == '__main__':
  66. d1 = MyDate(2024, 3, 15)
  67. d2 = MyDate(2024, 3, 17)
  68. print(d1 <= d2) # True
  69. print(d1 <= date(2024, 3, 15)) # True
  70. # 5、时间比较
  71. from datetime import time
  72. class MyTime:
  73. def __init__(self, hour, minute, second=0):
  74. self.value = time(hour, minute, second)
  75. def __le__(self, other):
  76. if isinstance(other, MyTime):
  77. return self.value <= other.value
  78. elif isinstance(other, time):
  79. return self.value <= other
  80. else:
  81. return NotImplemented
  82. if __name__ == '__main__':
  83. t1 = MyTime(10, 30)
  84. t2 = MyTime(11, 15)
  85. print(t1 <= t2) # True
  86. print(t1 <= time(10, 30)) # True
  87. # 6、价格比较
  88. class Price:
  89. def __init__(self, amount):
  90. self.amount = amount
  91. def __le__(self, other):
  92. if isinstance(other, Price):
  93. return self.amount <= other.amount
  94. elif isinstance(other, (int, float)):
  95. return self.amount <= other
  96. else:
  97. return NotImplemented
  98. if __name__ == '__main__':
  99. p1 = Price(10.99)
  100. p2 = Price(20.99)
  101. print(p1 <= p2) # True
  102. print(p2 <= 15.00) # False
  103. # 7、分数排名比较
  104. class StudentRank:
  105. def __init__(self, rank):
  106. self.rank = rank
  107. def __le__(self, other):
  108. if isinstance(other, StudentRank):
  109. return self.rank <= other.rank
  110. elif isinstance(other, int):
  111. return self.rank <= other
  112. else:
  113. return NotImplemented
  114. if __name__ == '__main__':
  115. r1 = StudentRank(1)
  116. r2 = StudentRank(5)
  117. print(r1 <= r2) # True
  118. print(r1 <= 3) # True
  119. # 8、版本比较
  120. import packaging.version
  121. class MyVersion:
  122. def __init__(self, version_str):
  123. self.value = packaging.version.parse(version_str)
  124. def __le__(self, other):
  125. if isinstance(other, MyVersion):
  126. return self.value <= other.value
  127. elif isinstance(other, str):
  128. return self.value <= packaging.version.parse(other)
  129. else:
  130. return NotImplemented
  131. if __name__ == '__main__':
  132. v1 = MyVersion("1.0.0")
  133. v2 = MyVersion("2.0.0")
  134. print(v1 <= v2) # True
  135. print(v1 <= "1.1.0") # True

43、__len__方法

43-1、语法
  1. __len__(self, /)
  2. Return len(self)
43-2、参数

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

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

43-3、功能

        用于返回容器对象(如列表、元组、字典、字符串、集合以及用户定义的容器类)中元素的数量。

43-4、返回值

        返回一个整数,表示对象的长度。

43-5、说明

        如果没有返回整数或者引发异常,那么使用len()函数时会抛出异常。

43-6、用法
  1. # 043、__len__方法:
  2. # 1、简单的列表包装器
  3. class MyListWrapper:
  4. def __init__(self, lst):
  5. self.lst = lst
  6. def __len__(self):
  7. return len(self.lst)
  8. # 2、字符串长度计算
  9. class StringLength:
  10. def __init__(self, s):
  11. self.s = s
  12. def __len__(self):
  13. return len(self.s)
  14. # 3、文件行数计算
  15. class FileLineCounter:
  16. def __init__(self, file_path):
  17. self.file_path = file_path
  18. def __len__(self):
  19. with open(self.file_path, 'r') as file:
  20. return sum(1 for _ in file)
  21. # 4、自定义集合
  22. class MySet:
  23. def __init__(self, items):
  24. self.items = set(items)
  25. def __len__(self):
  26. return len(self.items)
  27. # 5、范围计数器
  28. class RangeCounter:
  29. def __init__(self, start, end):
  30. self.start = start
  31. self.end = end
  32. def __len__(self):
  33. return self.end - self.start
  34. # 6、图形顶点数
  35. class Graph:
  36. def __init__(self, vertices):
  37. self.vertices = vertices
  38. def __len__(self):
  39. return len(self.vertices)
  40. # 7、用户列表(考虑重复)
  41. class UserList:
  42. def __init__(self, users):
  43. self.users = list(set(users)) # 去重
  44. def __len__(self):
  45. return len(self.users)
  46. # 8、单词列表(从文本中提取)
  47. class WordList:
  48. def __init__(self, text):
  49. self.words = text.split()
  50. def __len__(self):
  51. return len(self.words)
  52. # 9、数据库记录数
  53. class DatabaseRecords:
  54. def __init__(self, db_connection):
  55. self.db_connection = db_connection
  56. def __len__(self):
  57. # 假设这里有一个方法可以从数据库中获取记录数
  58. return self.db_connection.get_record_count()
  59. # 10、自定义字典(仅计算键的数量)
  60. class MyDict:
  61. def __init__(self, **kwargs):
  62. self.data = kwargs
  63. def __len__(self):
  64. return len(self.data.keys())
  65. # 11、日期范围中的天数
  66. from datetime import date, timedelta
  67. class DateRange:
  68. def __init__(self, start_date, end_date):
  69. self.start_date = start_date
  70. self.end_date = end_date
  71. def __len__(self):
  72. return (self.end_date - self.start_date).days + 1
  73. # 12、自定义树形结构中的节点数
  74. class TreeNode:
  75. def __init__(self, value, children=None):
  76. self.value = value
  77. self.children = children if children is not None else []
  78. def __len__(self):
  79. count = 1
  80. for child in self.children:
  81. count += len(child)
  82. return count

五、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、博客个人主页

遨游码海,我心飞扬
微信名片
注:本文转载自blog.csdn.net的神奇夜光杯的文章"https://myelsa1024.blog.csdn.net/article/details/139422325"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

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

分类栏目

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