• 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

  • 相关阅读:
    38) 收集centos所有版本镜像下载地址
    37) 查看linux 操作系统为多少位
    php面向对象高级应用一
    php form表单的验证+提交到数据库
    php获取form表单数据
    php form表单的提交
    php form表单概念
    php日期和时间的应用
    php日期和时间函数
    php字符串函数操作实例(2)
  • 原文地址:https://www.cnblogs.com/hluo/p/4056374.html
Copyright © 2020-2023  润新知