1. 子类继承父类实现
当需要继承父类的初始化的值时,使用 super().__init__()
.
class A:
def __init__(self):
self.x = 0
# B 继承 A
class B(A):
def __init__(self):
super().__init__()
self.y = 1
测试:
# 实例
cA = A()
print(cA.x)
cB = B()
print(cB.y)
print(cB.x)
运行结果:
0
1
0
若 类 B
没有 super().__init__()
会报错:
AttributeError: 'B' object has no attribute 'x'
2. 初始化并赋值变量
如果子类没有写__init__
函数,那么,就会采用父类中的__init__
函数;如果子类含有__int__
函数,由于 super
函数会对父类进行初始化,那么,子类和父类的__init__
函数都生效。如果子类和父类有相同的变量名,那么,以子类的为准。
示例:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class FooParent(object):
def __init__(self, b=2):
self.parent = 'I\'m the parent.'
self.b = b
def bar(self,message):
print ("%s from Parent" % message)
class FooChild(FooParent):
def __init__(self, c, b=1):
# super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象
super(FooChild,self).__init__(b=b)
self.c = c
def bar(self,message):
super(FooChild, self).bar(message)
print ('Child bar fuction')
print (self.parent)
if __name__ == '__main__':
fooChild = FooChild(c=3,b=1)
print("c,b", fooChild.c, fooChild.b)
运行结果:
c,b 3 1
这样,子类和父类的变量都完成了初始化。
最近开通了个公众号,主要分享python学习相关内容,推荐系统,风控等算法相关的内容,感兴趣的伙伴可以关注下。
公众号相关的学习资料会上传到QQ群596506387,欢迎关注。
参考: