先看下未加入 super().__init__()
函数时的程序运行结果:
class Function1(object):
def __init__(self):
self._weight = 'function1属性'
print(self._weight, "已被调用")
def fun(self):
print("function1中定义的方法")
class Function2(Function1):
def __init__(self):
print("function2属性")
example = Function2()
example.fun()
example._weight
输出结果:
function2属性
function1中定义的方法
Traceback (most recent call last):
File "D:/My Project/PycharmProjects/BuildCNNNetwork/main.py", line 17, in <module>
example._weight
AttributeError: 'Function2' object has no attribute '_weight'
Process finished with exit code 1
程序输出为 Function2 没有属性 _weight
,所以无法调用 _weight
的值,但 Function2 仍然可以调用 Function1 中的函数 fun
。
我们现在加入这个 super().__init__()
函数
class Function1(object):
def __init__(self):
self._weight = 'function1属性'
print(self._weight, "已被调用")
def fun(self):
print("function1中定义的方法")
class Function2(Function1):
def __init__(self):
super(Function2, self).__init__() # 可简写为 super().__init__()
print("function2属性")
example = Function2()
example.fun()
example._weight
输出结果:
function1属性 已被调用
function2属性
function1中定义的方法
Process finished with exit code 0
在加上该函数后,Function2 函数具备了 Function1 函数的属性,也即是 Function2 继承了父类 Function1 的属性。
下面再改动下:
class Function1(object):
def __init__(self):
self._weight = 'function1属性'
print(self._weight, "已被调用")
def fun(self):
print("function1中定义的方法")
class Function2(Function1):
def __init__(self):
super(Function2, self).__init__() # 可简写为 super().__init__()
print("function2属性")
example = Function2()
example.fun()
example._weight
print(example._weight)
输出结果:
function1属性 已被调用
function2属性
function1中定义的方法
function1属性
Process finished with exit code 0
当使用 print(example._weight)
之后,程序输出了 example._weight
的值: function1属性,说明 Function2 调用 Function1 的属性成功。