zoukankan      html  css  js  c++  java
  • 大坑

    1  class Parent(object):
    2    def altered(self):
    3      print "PARENT altered()"
    4  class Child(Parent):
    5    def altered(self):
    6      print "CHILD, BEFORE PARENT altered()"
    7   super(Child, self).altered()
    8      print "CHILD, AFTER PARENT altered()"
    9  dad = Parent()
    10  son = Child()
    11  dad.altered()
    12  son.altered()
    重要的是 9 到 11 行,当调用 son.altered() 时:
    1. 由于我覆写了 Parent.altered ,实际运行的是 Child.altered ,所以第 9 行执行结果是预料之中
    的。
    2. 这里我想在前面和后面加一个动作,所以,第 9 行之后,我要用 super 来获取 Parent.altered
    这个版本。
    3. 第 10 行我调用了 super(Child, self).altered() ,这和你过去用过的 getattr 很
    相似,不过它还知道你的继承关系,并且会访问到 Parent 类。这句你可以读作“调用 super 并
    且加上 Child 和 self 这两个参数,在此返回的基础上然后调用 altered ”。
    4. 到这里 Parent.altered 就会被运行,而且打印出了父类里的信息。
    5. 最后从 Parent.altered 返回到 Child.altered ,函数接着打印出来后面的信息。
    运行的结果是这样的:
    PARENT altered()
    CHILD, BEFORE PARENT altered()
    PARENT altered()
    CHILD, AFTER PARENT altered()
  • 相关阅读:
    7-4
    7-3
    第五章例5-2
    第五章例5-1
    第四章例4-12
    第四章例4-11
    第四章例4-10
    第四章例4-9
    第四章例4-8
    第四章例4-7
  • 原文地址:https://www.cnblogs.com/sageskr/p/4084279.html
Copyright © 2011-2022 走看看