首页 > 代码库 > Exercise 44: Inheritance Vs. Composition
Exercise 44: Inheritance Vs. Composition
class Parent(object): def __init__(self, **kwargs): if kwargs.has_key(‘age‘): self.__age = kwargs[‘age‘] if kwargs.has_key(‘sex‘): self.sex = kwargs[‘sex‘] def implicit(self): print "PARENT implicit()" def get_age(self): print self.__ageclass Child(Parent): passdad = Parent(sex = ‘male‘, age = 45)son = Child()dad.implicit()son.implicit()
解析**kwargs: http://stackoverflow.com/questions/5624912/kwargs-parsing-best-practice
两个下划线__开头为私有变量或私有函数。
class Parent(object): def altered(self): print "PARENT altered()"class Child(Parent): def altered(self): print "CHILD, BEFORE PARENT altered()" super(Child, self).altered() print "CHILD, AFTER PARENT altered()"dad = Parent()son = Child()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 Child(object): 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()
合成composition
Exercise 44: Inheritance Vs. Composition
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。