当前位置:   article > 正文

Python super().__init__()测试及理解_"class fan: def init (self) : 3 print(\"fun. init(

"class fan: def init (self) : 3 print(\"fun. init()\" 4 def test(self): 5 p"

Python super().__init__()含义(单继承,即只有一个父类)

测试一、我们尝试下面代码,没有super(A, self).__init__()时调用A的父类Root的属性方法(方法里不对Root数据进行二次操作)

class Root(object):
    def __init__(self):
        self.x= '这是属性'

    def fun(self):
    	#print(self.x)
        print('这是方法')
        
class A(Root):
    def __init__(self):
        print('实例化时执行')

test = A()		#实例化类
test.fun()	#调用方法
test.x		#调用属性

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

下面是结果:

Traceback (most recent call last):
实例化时执行
这是方法
  File "/hom/PycharmProjects/untitled/super.py", line 17, in <module>
    test.x  # 调用属性
AttributeError: 'A' object has no attribute 'x'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

可以看到此时父类的方法继承成功,可以使用,但是父类的属性却未继承,并不能用

测试二、我们尝试下面代码,没有super(A,self).__init__()时调用A的父类Root的属性方法(方法里Root数据进行二次操作)

class Root(object):
    def __init__(self):
        self.x= '这是属性'

    def fun(self):
    	print(self.x)
        print('这是方法')
        
class A(Root):
    def __init__(self):
        print('实例化时执行')

test = A()		#实例化类
test.fun()	#调用方法
test.x		#调用属性

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

结果如下

Traceback (most recent call last):
  File "/home/PycharmProjects/untitled/super.py", line 16, in <module>
    test.fun()  # 调用方法
  File "/home/PycharmProjects/untitled/super.py", line 6, in fun
    print(self.x)
AttributeError: 'A' object has no attribute 'x'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

可以看到此时报错和测试一相似,果然,还是不能用父类的属性

测试三、我们尝试下面代码,加入super(A, self).__init__()时调用A的父类Root的属性方法(方法里Root数据进行二次操作)

class Root(object):
    def __init__(self):
        self.x = '这是属性'

    def fun(self):
        print(self.x)
        print('这是方法')


class A(Root):
    def __init__(self):
        super(A,self).__init__()
        print('实例化时执行')


test = A()  # 实例化类
test.fun()  # 调用方法
test.x  # 调用属性

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

结果输出如下

实例化时执行
这是属性
这是方法
  • 1
  • 2
  • 3

此时A已经成功继承了父类的属性,所以super().__init__()的作用也就显而易见了,就是执行父类的构造函数,使得我们能够调用父类的属性。

上面是单继承情况,我们也会遇到多继承情况,用法类似,但是相比另一种Root.__init__(self),在继承时会跳过重复继承,节省了资源。

还有很多关于super的用法可以参考
super的使用

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/329371
推荐阅读
相关标签
  

闽ICP备14008679号