码迷,mamicode.com
首页 > 其他好文 > 详细

Exercise 44: Inheritance Vs. Composition

时间:2014-10-28 11:58:51      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   os   ar   for   sp   

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.__age
class Child(Parent):
    pass

dad = 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

标签:style   blog   http   io   color   os   ar   for   sp   

原文地址:http://www.cnblogs.com/hluo/p/4056374.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!