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

1、

https://blog.csdn.net/qq_38787214/article/details/87902291?utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control

2、https://www.runoob.com/w3cnote/python-super-detail-intro.html

3、

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 #调用属性

下面是结果:

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

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

测试二、我们尝试下面代码,没有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 #调用属性

结果如下

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'

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

测试三、我们尝试下面代码,加入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 # 调用属性



结果输出如下

实例化时执行
这是属性
这是方法

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

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

还有很多关于super的用法可以参考
super的使用
————————————————
版权声明:本文为CSDN博主「红鲤鱼与彩虹」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_38787214/article/details/87902291

2、

原文地址:https://www.cnblogs.com/yaok430/p/15006726.html