<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>运算符重载 on 老张开工了</title>
    <link>/%E8%BF%90%E7%AE%97%E7%AC%A6%E9%87%8D%E8%BD%BD/</link>
    <description>Recent content in 运算符重载 on 老张开工了</description>
    <generator>Hugo</generator>
    <language>zh-cn</language>
    <lastBuildDate>Sun, 17 May 2026 00:00:00 +0000</lastBuildDate>
    <atom:link href="/%E8%BF%90%E7%AE%97%E7%AC%A6%E9%87%8D%E8%BD%BD/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>魔法方法与运算符重载</title>
      <link>/posts/2026/05/magic-methods/</link>
      <pubDate>Sun, 17 May 2026 00:00:00 +0000</pubDate>
      <guid>/posts/2026/05/magic-methods/</guid>
      <description>魔法方法（Magic Methods）是 Python 中以双下划线开头和结尾的特殊方法，它们让自定义对象能够与 Python 的内置操作无缝集成。通过实现魔法方法，你可以让自己的类支持 +、[]、len()、for...in 等语法，让代码更加自然和 Pythonic。&#xA;魔法方法概述 魔法方法也被称为 dunder 方法（double underscore 的缩写）。它们不需要手动调用——Python 在特定操作时会自动触发。&#xA;class Demo: def __init__(self, value): self.value = value def __str__(self): return f&amp;#34;Demo({self.value})&amp;#34; def __len__(self): return len(str(self.value)) d = Demo(42) print(str(d)) # 触发 __str__ print(len(d)) # 触发 __len__ 对象的生命周期管理 __new__：真正的构造函数 __new__ 在 __init__ 之前调用，负责创建并返回实例。它通常只在需要控制对象创建时才会被重写：&#xA;class Singleton: &amp;#34;&amp;#34;&amp;#34;单例模式：全局只有一个实例&amp;#34;&amp;#34;&amp;#34; _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance def __init__(self, value: int): # 注意：每次调用 Singleton() 都会执行 __init__ self.</description>
    </item>
  </channel>
</rss>
