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()
  • 相关阅读:
    rt_list_entry() 函数
    替换空格
    跳台阶
    斐波那契数列
    基于5221码的同步十进制加法计数器
    强连通分量+Tarjia+缩点
    次小生成树
    差分约束
    P1547 Out of Hay
    P1197 [JSOI2008]星球大战
  • 原文地址:https://www.cnblogs.com/dollarzhaole/p/2977766.html
Copyright © 2011-2022 走看看