zoukankan      html  css  js  c++  java
  • 重新梳理Python基础(11)

    1. python中的继承

    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() #注意super的用法!!!!
            print "CHILD, AFTER PARENT altered()"
    
    dad = Parent()
    son = Child()
    
    dad.implicit()
    son.implicit()
    
    dad.override()
    son.override()
    
    dad.altered()
    son.altered()

    python可以多重继承,即一个class可以有多个父类。

    class Son(Dad, Mum):
        pass

    这时,当调用super(Son, self).***()的时候,会看Dad里有没有这个方法,如果有,就不调用Mum里的了,如果没有,才查看Mum里有没有,看下面的代码:

    class Parent(object):
    
        def override(self):
            print "PARENT override"
    
        def implicit(self):
            print "PARENT implicit"
    
        def altered(self):
            print "PARENT altered"
    
    class Mum(object):
        def altered1(self):
            print "MUM, altered."
    
    class Child(Mum, Parent):
    
        def override(self):
            print "CHILD override"
    
        def altered(self):
            print "CHILD, BEFORE PARENT altered()"
            super(Child, self).altered1()
            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()

    输出结果:

    E:\SkyDrive\python\the hard way to learn python>python ex44_4.py
    PARENT implicit
    PARENT implicit
    PARENT override
    CHILD override
    PARENT altered
    CHILD, BEFORE PARENT altered()
    MUM, altered.
    PARENT altered
    CHILD, AFTER PARENT altered()
  • 相关阅读:
    C# Bitmap类型与Byte[]类型相互转化
    我所理解的JavaScript闭包
    从零开始编写自己的C#框架 ---- 系列文章
    巧用Windows 7计划任务设置定时提醒
    vba中MsgBox的参数及用法
    SQL行转列和列转行
    web应用程序 ---- 日志系统的设计
    《代码整洁之道》读书笔记
    使用Excel制作万年历(日历可A4纸打印)
    C#窗体全屏功能
  • 原文地址:https://www.cnblogs.com/dollarzhaole/p/2977766.html
Copyright © 2011-2022 走看看