返回顶部
分享到

Python中的魔术方法__new__介绍

Mysql 来源:互联网 作者:佚名 发布时间:2025-05-24 23:05:35 人浏览
摘要

一、核心意义与机制 1.1 构造过程原理 1.2 与 __init__ 对比 特性 __new__ __init__ 方法类型 静态方法 实例方法 返回值 必须返回实例对象 无返回值 调用时机 创建实例时首先调用 在 __new__ 之后调用

一、核心意义与机制

1.1 构造过程原理

1.2 与 __init__ 对比

特性 __new__ __init__
方法类型 静态方法 实例方法
返回值 必须返回实例对象 无返回值
调用时机 创建实例时首先调用 在 __new__ 之后调用
主要职责 控制实例创建过程 初始化实例属性

二、核心功能解析

2.1 核心能力

  • 控制实例创建过程
  • 决定是否生成新实例
  • 修改实例创建逻辑
  • 实现设计模式底层支持

2.2 方法签名

元类中的 __new__ 参数(示例 4.1)

  • 样例

1

2

3

4

class Meta(type):

    def __new__(mcs, name, bases, attrs):

        # 参数列表固定

        return super().__new__(mcs, name, bases, attrs)

  • 参数解析表
参数名 类型 说明
mcs type 元类自身(约定命名,类似 cls 代表类)
name str 要创建的类名(如 "MyClass")
bases tuple 基类列表(继承的父类)
attrs dict 类属性字典(包含方法、类变量等)

调用逻辑

  • 元类用于??创建类对象??(不是实例对象)
  • 参数由解释器在定义类时自动传入
  • super().__new__ 最终调用 type.__new__ 生成类对象

不可变类型子类的 __new__(示例 3.2)

样例

1

2

3

class ImmutableStr(str):

    def __new__(cls, value):

        return super().__new__(cls, processed_value)

  • 参数解析表
参数名 类型 说明
cls type 当前类对象(ImmutableStr)
value Any 用户自定义参数(初始化输入值)

调用逻辑

  • 继承自不可变类型(str/int/tuple 等)
  • 必须通过 __new__ 完成实例创建
  • super().__new__ 调用父类(str)的构造方法
  • 参数需匹配父类 __new__ 的要求(如 str 需要传入初始化字符串)

可变类型普通类的 __new__(示例 3.1)

样例

1

2

3

class Singleton:

    def __new__(cls, *args, ?**?kwargs):

        return super().__new__(cls)

  • 参数解析表
参数名 类型 说明
cls ` 当前类对象(Singleton)
*args tuple 位置参数(与 __init__ 共享参数)
?**?kwargs dict 关键字参数(与 __init__ 共享参数)

调用逻辑

  • 普通类的实例创建流程
  • super().__new__ 调用 object.__new__ 生成实例
  • 参数需与 __init__ 方法兼容

2.3 参数传递关系图示

2.4 核心记忆要点

??元类 __new__ 的四个参数是固定结构??

  • 用于构建类对象(类的模板)
  • 参数由解释器自动填充

??普通类 __new__ 第一个参数必为 cls??

  • 后续参数需与 __init__ 匹配
  • 不可变类型需要完全重写参数列表

??super().__new__ 的参数必须与父类一致??

  • 元类中:super().__new__(mcs, name, bases, attrs)
  • 普通类中:super().__new__(cls[, ...])

三、典型应用场景

3.1 单例模式实现

1

2

3

4

5

6

7

8

9

10

11

class Singleton:

    _instance = None

     

    def __new__(cls, *args, ?**?kwargs):

        if not cls._instance:

            cls._instance = super().__new__(cls)

        return cls._instance

 

a = Singleton()

b = Singleton()

print(a is b)  # True

3.2 不可变类型扩展

1

2

3

4

5

6

7

8

class ImmutableStr(str):

    def __new__(cls, value):

        # 预处理字符串

        processed = value.strip().upper()

        return super().__new__(cls, processed)

     

s = ImmutableStr("  hello  ")

print(s)  # "HELLO"

3.3 对象池技术

1

2

3

4

5

6

7

8

9

10

11

12

13

class ConnectionPool:

    _pool = []

    _max_size = 5

     

    def __new__(cls):

        if len(cls._pool) < cls._max_size:

            obj = super().__new__(cls)

            cls._pool.append(obj)

            return obj

        return cls._pool.pop(0)

 

conn1 = ConnectionPool()

conn2 = ConnectionPool()

四、高级应用技巧

4.1 元类协作

1

2

3

4

5

6

7

8

9

10

class Meta(type):

    def __new__(mcs, name, bases, attrs):

        # 添加类属性

        attrs['version'] = 1.0

        return super().__new__(mcs, name, bases, attrs)

 

class MyClass(metaclass=Meta):

    pass

 

print(MyClass.version)  # 1.0

4.2 参数预处理

1

2

3

4

5

6

7

8

class SmartTuple(tuple):

    def __new__(cls, iterable):

        # 过滤非数字元素

        filtered = (x for x in iterable if isinstance(x, (int, float)))

        return super().__new__(cls, filtered)

     

t = SmartTuple([1, 'a', 3.14, None])

print(t)  # (1, 3.14)

五、继承体系中的使用

5.1 继承链处理

1

2

3

4

5

6

7

8

9

class Base:

    def __new__(cls, *args, ?**?kwargs):

        print(f"Creating {cls.__name__}")

        return super().__new__(cls)

 

class Child(Base):

    pass

 

c = Child()  # 输出 "Creating Child"

5.2 多继承处理

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

class A:

    def __new__(cls, *args, ?**?kwargs):

        print("A's __new__")

        return super().__new__(cls)

 

class B:

    def __new__(cls, *args, ?**?kwargs):

        print("B's __new__")

        return super().__new__(cls)

 

class C(A, B):

    def __new__(cls, *args, ?**?kwargs):

        return A.__new__(cls)

 

obj = C()  # 输出 "A's __new__"

六、注意事项与调试

6.1 常见错误

1

2

3

4

5

6

7

8

9

class ErrorCase:

    def __new__(cls):

        # 错误:忘记返回实例

        print("Creating instance")  # ? 无返回值

         

    def __init__(self):

        print("Initializing")

 

e = ErrorCase()  # TypeError

6.2 调试技巧

1

2

3

4

5

6

7

8

9

10

11

class DebugClass:

    def __new__(cls, *args, ?**?kwargs):

        print(f"__new__ args: {args}")

        instance = super().__new__(cls)

        print(f"Instance ID: {id(instance)}")

        return instance

     

    def __init__(self, value):

        print(f"__init__ value: {value}")

 

d = DebugClass(42)

七、性能优化建议

7.1 对象缓存策略

1

2

3

4

5

6

7

8

9

10

11

12

13

14

class ExpensiveObject:

    _cache = {}

     

    def __new__(cls, config):

        key = hash(frozenset(config.items()))

        if key not in cls._cache:

            instance = super().__new__(cls)

            instance._init(config)

            cls._cache[key] = instance

        return cls._cache[key]

     

    def __init__(self, config):

        # 避免重复初始化

        self.config = config

最佳实践总结??

  • 优先使用 super().__new__ 保证继承链正常
  • 修改不可变类型必须使用 __new__
  • 单例模式要处理好线程安全问题
  • 避免在 __new__ 中做耗时操作

版权声明 : 本文内容来源于互联网或用户自行发布贡献,该文观点仅代表原作者本人。本站仅提供信息存储空间服务和不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权, 违法违规的内容, 请发送邮件至2530232025#qq.cn(#换@)举报,一经查实,本站将立刻删除。
原文链接 :
相关文章
  • Python虚拟环境终极(含PyCharm的使用教程)

    Python虚拟环境终极(含PyCharm的使用教程)
    一、为什么需要虚拟环境? 场景 问题表现 虚拟环境解决方案 多项目依赖冲突 项目A需要Django 3.2,项目B需要Django 4.1 隔离不同项目的依赖版
  • Python中的魔术方法__new__介绍

    Python中的魔术方法__new__介绍
    一、核心意义与机制 1.1 构造过程原理 1.2 与 __init__ 对比 特性 __new__ __init__ 方法类型 静态方法 实例方法 返回值 必须返回实例对象 无返回值
  • 基于PyQt5实现的Windows定时关机工具

    基于PyQt5实现的Windows定时关机工具
    在日常使用电脑的过程中,我们经常会遇到需要定时关机的场景,比如: 夜间下载文件,想让电脑在任务完成后自动关机。 长时间运行的程
  • 宝塔安装的MySQL无法连接的情况及解决方案

    宝塔安装的MySQL无法连接的情况及解决方案
    一、错误 1130:Host xxx.xxx.xxx.xxx is not allowed to connect to this MySQL server 错误原因 此错误表示您的 IP 地址没有被授权访问宝塔服务器上的 MySQL。
  • MySQL中drop、truncate和delete的区别
    对于drop、truncate和delete,虽然简单,但是真要使用或者面试时候问到还是需要有一定的总结,今天来简单讲讲他们直接的区别。在此之前先
  • Linux搭建单机MySQL8.0.26版本的操作方法

    Linux搭建单机MySQL8.0.26版本的操作方法
    环境信息 IP 系统 规格 10.0.0.10 Ubuntu22.04 2c4g 数据库服务安装步骤 下载前置依赖 1 2 # 下载libtinfo5、libnuma1依赖 [root@lb ~]# apt update -y apt install
  • mysql中的group by高级用法
    MySQL中的GROUP BY是数据聚合分析的核心功能,主要用于将结果集按指定列分组,并结合聚合函数进行统计计算。以下从基本语法到高级用法进
  • MySQL双主搭建+keepalived高可用的实现

    MySQL双主搭建+keepalived高可用的实现
    一、测试环境准备 节点1 节点2 IP地址 192.168.101.77 192.168.101.79 MySQL版本 8.0.32 8.0.32 二、主从搭建 1.创建复制用户 节点1执行: 1 2 3 4 mysql CREA
  • MYSQL数据表基本操作之创建+查看+修改+删除操作方

    MYSQL数据表基本操作之创建+查看+修改+删除操作方
    在数据库管理中,数据表的创建、查看、修改和删除是最基本的操作。这些操作是日常数据库管理和维护中不可或缺的一部分,正确理解和
  • MySQL使用SHOW PROCESSLIST的实现
    1、SHOW PROCESSLIST 显示进程列表 SHOW [FULL] PROCESSLIST 用于查看当前MySQL服务器上的所有运行中的进程列表信息。这个命令可以帮助我们了解哪些
  • 本站所有内容来源于互联网或用户自行发布,本站仅提供信息存储空间服务,不拥有版权,不承担法律责任。如有侵犯您的权益,请您联系站长处理!
  • Copyright © 2017-2022 F11.CN All Rights Reserved. F11站长开发者网 版权所有 | 苏ICP备2022031554号-1 | 51LA统计