python-magic-function

magic function

magic function是python高级用法,python中以双下划线开头和结尾的方法,允许类定义与python内置操作符和函数交互的行为。

经典使用操作

1、构造与初始化

class MyClass:
    def __new__(cls, *args, **kwargs):
        """创建实例时首先调用,通常用于不可变类型或单例模式"""
        instance = super().__new__(cls)
        print("__new__ called")
        return instance
    
    def __init__(self, value):
        """初始化实例属性"""
        self.value = value
        print(f"__init__ called with value: {value}")
    
    def __del__(self):
        """对象销毁时调用"""
        print("__del__ called")

# 最佳实践:
# - 在 __init__ 中进行属性初始化
# - __new__ 通常不需要重写,除非特殊需求
# - 避免依赖 __del__ 进行重要资源清理,使用 with 语句和上下文管理器

最佳实践:init中进行属性初始化、new只有单例或者不可变类型时进行重写、避免以来del进行清理

2、比较操作

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    # def __eq__(self, other):
    #     """等于"""
    #     if not isinstance(other, Vector):
    #         return NotImplemented
    #     return self.x == other.x and self.y == other.y
    
    def __lt__(self, other):
        """小于"""
        if not isinstance(other, Vector):
            return NotImplemented
        return (self.x**2 + self.y**2) < (other.x**2 + other.y**2)
    
    def __le__(self, other):
        """小于等于"""
        return self < other or self == other
    
    # 其他比较方法:__ne__, __gt__, __ge__
    
    def __hash__(self):
        """使对象可哈希(可用于字典键)"""
        return hash((self.x, self.y))

    a = Vector(2, 2)
    b = Vector(2, 2)

    c = a < b # false
    print(c)

    a = Vector(1, 2)
    b = Vector(2, 2)

    c = a < b # true
    print(c)

    print(hash(a)) # 返回一个哈希值
    ntr = {
        a: 'nihao',
        b: 'nixhis'
    }
    print(ntr[a])
posted @ 2026-01-30 00:34  LemHou  阅读(3)  评论(0)    收藏  举报