1. 程式人生 > >Python3基礎 super 子類調用父類的__init__

Python3基礎 super 子類調用父類的__init__

ubunt RoCE projects 平臺 子類 根據 調用 積累 har

?

  • python : 3.7.0
  • OS : Ubuntu 18.04.1 LTS
  • IDE : PyCharm 2018.2.4
  • conda : 4.5.11
  • type setting : Markdown

?

example_1

code

"""
@Author : 行初心
@Date   : 18-9-23
@Blog   : www.cnblogs.com/xingchuxin
@GitHub : github.com/GratefulHeartCoder
"""


class Parent:
    def __init__(self):
        # 父類的構造函數
        print("父類構造完畢")


class Child1(Parent):
    # child1類繼承於 parent類
    def __init__(self):
        print("子類1代構造函數")


class Child2(Child1):
    # child2類繼承於 child1類
    def __init__(self):
        print("子類2代構造函數")


def main():
    # 父類的構造函數不會出現,子類1代的構造函數也不會出現
    Child2()


if __name__ == ‘__main__‘:
    main()

result

/home/xcx/anaconda3/envs/xingchuxin/bin/python /home/xcx/PycharmProjects/oop/demo.py
子類2代構造函數

Process finished with exit code 0

?

example_2

code

"""
@Author : 行初心
@Date   : 18-9-23
@Blog   : www.cnblogs.com/xingchuxin
@GitHub : github.com/GratefulHeartCoder
"""


class Parent:
    def __init__(self):
        # 父類的構造函數
        print("父類構造完畢")


class Child1(Parent):
    # child1類繼承於 parent類
    def __init__(self):
        print("子類1代構造函數")


class Child2(Child1):
    # child2類繼承於 child1類
    def __init__(self):
        super().__init__()
        print("子類2代構造函數")


def main():
    # 構造函數有了super()才能追本溯源呀,但是。。。Child1沒有super
    Child2()


if __name__ == ‘__main__‘:
    main()

result

/home/xcx/anaconda3/envs/xingchuxin/bin/python /home/xcx/PycharmProjects/oop/demo.py
子類1代構造函數
子類2代構造函數

Process finished with exit code 0

?

example_3

code

"""
@Author : 行初心
@Date   : 18-9-23
@Blog   : www.cnblogs.com/xingchuxin
@GitHub : github.com/GratefulHeartCoder
"""


class Parent:
    def __init__(self):
        # 父類的構造函數
        print("父類構造完畢")


class Child1(Parent):
    # child1類繼承於 parent類
    def __init__(self):
        super().__init__()
        print("子類1代構造函數")


class Child2(Child1):
    # child2類繼承於 child1類
    def __init__(self):
        super().__init__()
        print("子類2代構造函數")


def main():
    # 每一級都有super才好呢
    Child2()


if __name__ == ‘__main__‘:
    main()

result

/home/xcx/anaconda3/envs/xingchuxin/bin/python /home/xcx/PycharmProjects/oop/demo.py
父類構造完畢
子類1代構造函數
子類2代構造函數

Process finished with exit code 0

?

more knowledge

  • [2018-09-24]
    註意看:在繼承中是 先調用父類的構造函數,還是先調用子類的構造函數?

?

resource

  • [文檔] https://docs.python.org/3/
  • [規範] https://www.python.org/dev/peps/pep-0008/
  • [規範] https://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_language_rules/
  • [源碼] https://www.python.org/downloads/source/
  • [ PEP ] https://www.python.org/dev/peps/
  • [平臺] https://www.cnblogs.com/

?

tips

行初心 會根據所學的知識,對博文進行更新。
該博文地址:https://www.cnblogs.com/xingchuxin/p/9695513.html

?


Python具有開源、跨平臺、解釋型、交互式等特性,值得學習。
Python的設計哲學:優雅,明確,簡單。提倡用一種方法,最好是只有一種方法來做一件事。
代碼的書寫要遵守規範,這樣有助於溝通和理解。
每種語言都有獨特的思想,初學者需要轉變思維、踏實踐行、堅持積累。

Python3基礎 super 子類調用父類的__init__