比较一下继承和组合,ex44py:
#!/usr/bin/python
# -*- coding: utf-8 -*-
#继承
class Parent(object):
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(Child, self).altered()
print "CHILD, AFTER PARENT altered()"
dad = Parent()
son = Child()
dad.implicit()
son.implicit()
dad.override()
son.override()
dad.altered()
son.altered()
#组合
class Other(object):
def override(self):
print "OTHER override()"
def implicit(self):
print "OTHER implicit()"
def altered(self):
print "OTHER altered()"
class Othis(object):
def __init__(self):
self.other = Other()
def implicit(self):
self.other.implicit()
def override(self):
print "OTHIS override()"
def altered(self):
print "OTHIS, BEFORE OTHER altered()"
self.other.altered()
print "OTHIS, AFTER OTHER altered()"
son = Othis()
son.implicit()
son.override()
son.altered()
有如下输出:
PARENT implicit()
PARENT implicit()
PARENT override()
CHILD override()
PARENT altered()
CHILD, BEFORE PARENT altered()
PARENT altered()
CHILD, AFTER PARENT altered()
OTHER implicit()
OTHIS override()
OTHIS, BEFORE OTHER altered()
OTHER altered()
OTHIS, AFTER OTHER altered()