Python繼承過程的__init__方法

牛平發表於2016-04-22
目的:此文的目的在於理解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部落格 ” ,連結:http://blog.itpub.net/29757574/viewspace-2086179/,如需轉載,請註明出處,否則將追究法律責任。

相關文章