程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-06(2)

Python3 super().__init__()测试及理解

发布于2019-08-07 10:22     阅读(1025)     评论(0)     点赞(1)     收藏(4)


Python3 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的使用



所属网站分类: 技术文章 > 博客

作者:473847837423232

链接:https://www.pythonheidong.com/blog/article/9788/ca2c45fcf13ac4dc5ba3/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

1 0
收藏该文
已收藏

评论内容:(最多支持255个字符)