zoukankan      html  css  js  c++  java
  • 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.__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

  • 相关阅读:
    Android 5.X新特性之RecyclerView基本解析及无限复用
    Android 网络框架之Retrofit2使用详解及从源码中解析原理
    Android 源码解析之AsyncTask
    Business Logic
    WHO AM I
    黑洞
    俄罗斯方块
    还记得八皇后的解法吗
    汝之蜜糖,吾之砒霜
    项目为什么会失败
  • 原文地址:https://www.cnblogs.com/hluo/p/4056374.html
Copyright © 2011-2022 走看看