Python类中__new__()方法 和 __init__()方法区别

本文详细介绍了Python中__new__()和__init__()的区别。__new__()是一个静态方法,主要用来创建实例,它必须返回一个类的实例,而__init__()则在__new__()之后调用,用于初始化新创建的实例。两者协同工作以构造对象,__new__()创建对象,__init__()对其进行定制。如果不返回类的实例,__init__()将不会执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.__new__()方法

官方文档:

object.__new__(cls[, ...])

Called to create a new instance of class cls__new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of __new__() should be the new object instance (usually an instance of cls).

Typical implementations create a new instance of the class by invoking the superclass’s 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值