ITPub博客

首页 > 应用开发 > IT综合 > Python继承过程的__init__方法

Python继承过程的__init__方法

原创 IT综合 作者:牛平 时间:2016-04-22 16:48:43 0 删除 编辑
目的:此文的目的在于理解Python继承过程中的__init__方法,谨作小记

  1.子类继承父类时,如果__init__方法被重写,可以使用super函数调用父类的__init__方法,否则被改写的__init__方法会覆盖原有的自动继承的__init__方法。
  2.类的继承,就是子类继承除了构造函数之外的所有的东西,__init__方法不是构造方法(函数)
  3.子类继承父类时,__init__方法被自动继承,并在创建实例时,自动调用。
  1. 点击(此处)折叠或打开

    1. class A(object):
    2.     def __init__(self,message):
    3.         self.message=message;
    4. #B inherits from A without writing the function __init__,It just define a function called getmessag
    5. #e,So,the init will be inherited, the __init__ will be inherted by B by default
    6. # if you create b using B, the init will work and the "message" will be return.

    7. class B(A):
    8.     def getmessage(self):
    9.         return self.message

    10. b=B('B')

    11. print b.getmessage()


    12. #C inherit from A and rewrite the __init__function,
    13. #So the message will not be initialized and the c.getmessage will not work.

    14. #class C(A):
    15. # def __init__(self, message):
    16. # pass
    17. # def getmessage(self):
    18. # return self.message


    19. #c=C('C')

    20. #print c.getmessage()

    21. #So the D inherit from A and using a method super( type, obj ), this can be unde
    22. #rstood like below, the super method find the D `s base class and change the self
    23. #to its super class, then using the "super(D,self)
    24. class D(A):
          def __init__(self,message):
              super(D,self).__init__(message)

          def getmessage(self):
              return self.message

      d=D('D')
      print d.getmessage()

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29757574/viewspace-2086179/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
一个在金融小企业瞎折腾的运维,梦想给小企业带来尽可能的标准化与自动化。

注册时间:2014-07-18

  • 博文量
    50
  • 访问量
    154495