# Python 教程 - 類繼承

Jinku Hu 2023年1月30日

``````class ParentClass:
# members

class ChildClass(ParentClass):
# members
``````

``````>>> class Auto:
def __init__(self, e, n):
self.engine = e
self.name = n
def display(self):
print("Name of Auto: ", self.name)
print("Engine of auto: ", self.engine)

>>> class Car(Auto):
def __init__(self):
self.x= input("Enter name of car: ")
self.y= input("Enter engine of car: ")
Auto.__init__(self,self.y,self.x)

>>> c = Car()
Enter name of car: Prius
Enter engine of car: 1.5l
>>> c.display()
Name of Auto:  Prius
Engine of auto:  1.5l
``````

`Car` 的建構函式內部，呼叫 `Auto` 的建構函式。`Car` 的物件可呼叫 `Auto` 的所有方法。

## Python 類繼承方法重寫

``````>>> class Auto:
def __init__(self, e, n):
self.engine = e
self.name = n
def display(self):
print("Name of Auto: ", self.name)
print("Engine of auto: ", self.engine)

>>> class Car(Auto):
def __init__(self):
self.x= input("Enter name of car: ")
self.y= input("Enter engine of car: ")
Auto.__init__(self,self.y,self.x)
def display(self):
print("You are in child class")

>>> c = Car()
Enter name of car: Prius
Enter engine of car: 1.5l
>>> c.display()
You are in child class
``````

## Python 類多重繼承

``````class A:
# members

class B:
# members

class child(A, B):
# members
``````

``````>>> class A:
def dispA(self):
print('You are in class A')

>>> class B:
def dispB(self):
print('You are in class B')

>>> class C(A, B):
def dispC(self):
print('You are in class C')

>>> Cobj = C()
>>> Cobj.dispA()
You are in class A

>>> Cobj.dispB()
You are in class B

>>> Cobj.dispC()
You are in class C
``````

## Python 類多級繼承

``````class A:
# members

class B(A):
# members

class C(B):
# members
``````

``````>>> class A:
def dispA(self):
print('You are in class A')

>>> class B(A):
def dispB(self):
print('You are in class B')

>>> class C(B):
def dispC(self):
print('You are in class C')

>>> Cobj = C()

>>> Cobj.dispA()
You are in class A

>>> Cobj.dispB()
You are in class B

>>> Cobj.dispC()
You are in class C
``````

DelftStack.com 創辦人。Jinku 在機器人和汽車行業工作了8多年。他在自動測試、遠端測試及從耐久性測試中創建報告時磨練了自己的程式設計技能。他擁有電氣/ 電子工程背景，但他也擴展了自己的興趣到嵌入式電子、嵌入式程式設計以及前端和後端程式設計。