Python __complex__ 方法
最后修改于 2025 年 4 月 8 日
这篇综合指南探讨了 Python 的 __complex__
方法,这个特殊方法使对象能够被转换为复数。我们将涵盖基本用法、数值运算、自定义实现和实际示例。
基本定义
__complex__
方法是 Python 中的一个特殊方法,它定义了对象应如何转换为复数。它由 complex()
内置函数以及在复数运算期间调用。
关键特征:它必须返回一个复数,用于隐式和显式转换,并启用数值互操作性。它是 Python 数值协议的一部分,与 __int__
和 __float__
一起。
基本的 __complex__ 实现
这是一个简单的实现,展示了 __complex__
如何启用转换为复数。该方法应返回一个内置的复数。
class ComplexNumber: def __init__(self, real, imag): self.real = real self.imag = imag def __complex__(self): return complex(self.real, self.imag) cn = ComplexNumber(3, 4) print(complex(cn)) # (3+4j) print(type(complex(cn))) # <class 'complex'>
这个例子展示了一个基本的复数包装类。__complex__
方法返回一个具有相同分量的内置复数。complex()
内置函数会调用此方法。
返回的值必须是 Python complex
类型。这可以与 Python 的数值运算和函数无缝集成。
将 __complex__ 与数学运算一起使用
__complex__
允许自定义对象参与复数运算。 Python 会在需要时自动转换它们。
class PolarNumber: def __init__(self, magnitude, angle): self.magnitude = magnitude self.angle = angle def __complex__(self): import math real = self.magnitude * math.cos(self.angle) imag = self.magnitude * math.sin(self.angle) return complex(real, imag) polar = PolarNumber(5, 0.927) # ~3+4j in rectangular native_complex = complex(1, 2) result = polar + native_complex print(result) # (4+6j)
这个 PolarNumber 类以极坐标形式存储复数,但通过 __complex__
转换为矩形形式。在加法运算期间,Python 会自动使用此转换。
当对象在与内置复数的运算中使用时,转换会隐式发生。 这保持了数学的正确性。
实现复数解析
__complex__
可以用于从字符串或其他格式实现自定义复数解析,同时保持兼容性。
class StringComplex: def __init__(self, complex_str): self.str = complex_str def __complex__(self): parts = self.str.split('+') real = float(parts[0]) imag = float(parts[1].rstrip('j')) return complex(real, imag) sc = StringComplex("3.5+4.2j") native = complex(sc) print(native) # (3.5+4.2j) print(native * 2) # (7+8.4j)
这个类从字符串解析复数,但通过 __complex__
提供标准的复数行为。 转换使所有复数运算都能正常工作。
该实现处理特定的字符串格式。 在实践中,您需要更强大的解析,但这显示了转换原则。
复数验证
__complex__
可以包含验证逻辑,以确保仅从您的对象创建有效的复数。
class ValidatedComplex: def __init__(self, real, imag): self.real = real self.imag = imag def __complex__(self): if not (isinstance(self.real, (int, float)) and isinstance(self.imag, (int, float))): raise ValueError("Components must be numeric") return complex(self.real, self.imag) vc = ValidatedComplex(3, 4) print(complex(vc)) # OK # vc_bad = ValidatedComplex("3", "4") # Raises ValueError
此实现检查两个分量在转换之前是否为数字。 这样可以防止创建无效的复数并提供早期错误检测。
验证发生在转换过程中而不是初始化过程中,从而可以在保持安全性的同时实现更灵活的用法模式。
将 __complex__ 与其他数值方法结合使用
__complex__
通常与其他数值特殊方法一起使用,为自定义类提供完整的数值行为。
class FullNumeric: def __init__(self, value): self.value = value def __complex__(self): return complex(self.value) def __int__(self): return int(self.value) def __float__(self): return float(self.value) def __add__(self, other): return FullNumeric(self.value + other) num = FullNumeric(3.5) print(complex(num) + 2j) # (3.5+2j) print(float(num) + 1.5) # 5.0 print(int(num) + 2) # 5
此类支持转换为所有 Python 数值类型并实现基本算术。 __complex__
与其他数值方法集成以实现完整的数值行为。
这种组合允许对象在保持类型安全性和数学正确性的同时,灵活地在数值上下文中使用。
最佳实践
- 返回正确的类型: 始终返回内置的复数
- 保持数学的正确性: 确保转换在数学上有效
- 实现相关方法: 考虑添加
__float__
和__int__
- 优雅地处理错误: 在转换之前验证数据
- 记录行为: 清楚地记录任何特殊的转换逻辑
资料来源
作者
列出所有 Python 教程。