class Parent():
def override(self):
print("parent override()")
def implicit(self):
print("parent implicit()")
def altered(self):
print("parent altered()")
class Child(Parent):
def override(self):
print("child override()")
def altered(self):
print("child, before parent altered()")
super().altered()
print("child, after parent altered()")
dad = Parent()
son = Child()
# 隐式继承,父类定义了implicit函数,但没有在子类中定义,子类会从父类继承所有的行为
dad.implicit()
son.implicit()
# 显示继承,子类override函数有一个不同的行为,从而实现子类的新功能。
dad.override()
son.override()
# 在运行前或运行后替换,在继承父类函数前或后再修改行为。使用python的内置函数super来调用父类里的函数。
dad.altered()
son.altered()
RESULT:
parent implicit()
parent implicit()
parent override()
child override()
parent altered()
child, before parent altered()
parent altered()
child, after parent altered()
- 在python2.7中,继承语法稍有不同,Son类定义类似于下面这样:
# 初始化
class Parent(object):
def __init__(self):
--snip--
class Son(Parent):
def __init__(self):
super(Son,self).__init__()
--snip--
或
# 无需初始化
class Parent(object):
def func(self):
--snip--
class Son(Parent):
def func(self):
super(Son,self).func()
--snip--
-
函数super()需要两个实参:子类名和对象self。为帮助Python将父类和子类关联起来,这些实参必不可少,另外,在Python2.7中使用继承是,务必在定义父类是在括号内指定object。
-
继承是一种有用的技术,但也可以直接使用别的类和模块实现同样功能。
class Other():
def override(self):
print("Other override()")
def implicit(self):
print("OTHER implicit()")
def altered(self):
print("OTHER altered()")
class Child():
def __init__(self):
self.other = Other()
def implicit(self):
self.other.implicit()
def override(self):
print("CHILD override()")
def altered(self):
print("CHILD, before OTHER altered()")
self.other.altered()
print("CHILD, after OTHER altered()")
son = Child()
son.implicit()
son.override()
son.altered()
RESULT:
OTHER implicit()
CHILD override()
CHILD, before OTHER altered()
OTHER altered()
CHILD, after OTHER altered()