Python中class的三种继承方法
class parent(object): def implicit(self): print("Parent implicit()") def override(self): print("Parent override()") def altered(self): print("Parent altered()") class child(parent): def override(self): print("Child override()") def altered(self): print("Child,Before Parent altered()") super(child,self).altered() print("Child,After Parent altered()") dad=parent() son=child() dad.implicit() son.implicit() dad.override() son.override() dad.altered() son.altered()
运行结果:
Parent implicit() Parent implicit() Parent override() Child override() Parent altered() Child,Before Parent altered() Parent altered() Child,After Parent altered()
还可以写成:
class parent(): def implicit(self): print("Parent implicit()") def override(self): print("Parent override()") def altered(self): print("Parent altered()") class child(parent): def __init__(self): self.parent =parent() def implicit(self): self.parent.implicit() def override(self): print("Child override()") def altered(self): print("Child,Before Parent altered()") super(child,self).altered() print("Child,After Parent altered()") dad=parent() son=child() dad.implicit() son.implicit() dad.override() son.override() dad.altered() son.altered()