Python(二)__init__和__new__和super()

本文深入探讨了Python中类构造的基本概念,包括__new__、__init__和super()的使用方法,并通过具体示例展示了这些函数如何在实例化过程中发挥作用。

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

基本概念

这三个都是和类相关的概念。 new 和 init是类在实例化过程中执行的函数。 super是在继承的情况下,执行某个被覆盖的程序的一个方法。 (多继承的原则: 广度优先)

  1. __new__: 实例化时,new一个实例出来的函数。
  2. __init__: 对new 返回的 实例进行初始化的函数。
  3. spuer(): 和__mro__ 配套的内容的函数。__mro__是一个list,是super执行顺序的list。

具体例子

1. new 和 init的例子

首先看代码,从代码看本质。

class Test():
    def __init__(self,*args,**kargs):
        print("__init__ start")

    def __new__(cls,*args,**kargs):
        print("__new__ start")
        return super().__new__(cls,*args,**kargs)

a = Test()

# 下面是print结果
__new__ start
__init__ start
复制代码

2.super的例子

老规矩,看代码. 下面的代码,可以看出,是按照__mro__ 的顺序执行的。

super有两种使用方式,第一,不带任何参数。按照__mro__顺序匹配。 第二,带两个参数的使用方法(type,objce_of_type), 在__mro__中的 参数 type 右边开始匹配。

class A:
    def __init__(self):
        self.n = 2

    def add(self,m):
        print("the ne in A is {}".format(self.n))
        self.n += m

class B(A):
    def __init__(self):
        self.n = 3

    def add(self,m):
        print("BEFORE the ne in B is {}".format(self.n))
        super().add(m)
        print("AFTER the ne in B is {}".format(self.n))
        self.n +=3

class C(A):
    def __init__(self):
        self.n = 3

    def add(self,m):
        print("BEFORE the ne in C is {}".format(self.n))
        super().add(m)
        print("AFTER the ne in C is {}".format(self.n))
        self.n +=4


class D(B, C):
    def __init__(self):
        self.n = 5

    def add(self, m):
        print('self is {0} @D.add'.format(self.n))
        super().add(2)
        self.n += 5
      

d = D()
d.add(2)
print(d.n)

# print result
self is 5 @D.add
BEFORE the ne in B is 5
BEFORE the ne in C is 5
the ne in A is 5
AFTER the ne in C is 7
AFTER the ne in B is 11
19

# __mro__
D.mro()
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]


# super 的用法
def super(cls, inst):
    mro = inst.__class__.mro()
    return mro[mro.index(cls) + 1]


class C(B):
    def method(self, arg):
        super().method(arg)    # This does the same thing as:
                               # super(C, self).method(arg)

复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值