Python(二)__init__和__new__和super()

基本概念

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

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

具体例子

1. new 和 init的例子

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

 
  1. class Test():

  2. def __init__(self,*args,**kargs):

  3. print("__init__ start")

  4.  
  5. def __new__(cls,*args,**kargs):

  6. print("__new__ start")

  7. return super().__new__(cls,*args,**kargs)

  8.  
  9. a = Test()

  10.  
  11. # 下面是print结果

  12. __new__ start

  13. __init__ start

  14. 复制代码

2.super的例子

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

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

 
  1. class A:

  2. def __init__(self):

  3. self.n = 2

  4.  
  5. def add(self,m):

  6. print("the ne in A is {}".format(self.n))

  7. self.n += m

  8.  
  9. class B(A):

  10. def __init__(self):

  11. self.n = 3

  12.  
  13. def add(self,m):

  14. print("BEFORE the ne in B is {}".format(self.n))

  15. super().add(m)

  16. print("AFTER the ne in B is {}".format(self.n))

  17. self.n +=3

  18.  
  19. class C(A):

  20. def __init__(self):

  21. self.n = 3

  22.  
  23. def add(self,m):

  24. print("BEFORE the ne in C is {}".format(self.n))

  25. super().add(m)

  26. print("AFTER the ne in C is {}".format(self.n))

  27. self.n +=4

  28.  
  29.  
  30. class D(B, C):

  31. def __init__(self):

  32. self.n = 5

  33.  
  34. def add(self, m):

  35. print('self is {0} @D.add'.format(self.n))

  36. super().add(2)

  37. self.n += 5

  38.  
  39.  
  40. d = D()

  41. d.add(2)

  42. print(d.n)

  43.  
  44. # print result

  45. self is 5 @D.add

  46. BEFORE the ne in B is 5

  47. BEFORE the ne in C is 5

  48. the ne in A is 5

  49. AFTER the ne in C is 7

  50. AFTER the ne in B is 11

  51. 19

  52.  
  53. # __mro__

  54. D.mro()

  55. [<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]

  56.  
  57.  
  58. # super 的用法

  59. def super(cls, inst):

  60. mro = inst.__class__.mro()

  61. return mro[mro.index(cls) + 1]

  62.  
  63.  
  64. class C(B):

  65. def method(self, arg):

  66. super().method(arg) # This does the same thing as:

  67. # super(C, self).method(arg)

  68.  
  69. 复制代码

相关资源:高斯光束传播及其MATLAB仿真.pdf

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值