xia的小窩

一起來coding和碼字吧

0%

pyclass-繼承

接下來我們開始玩繼承吧

1
class 子類 (父類) 

繼承(Inheritance)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class car:
def __init__(self):
self.color = "balck"
def drive(self):
print("The driver is Sam")

class Airplane(car):
def acc(self):
print("acc is already")

class buff(car):
def button(self):
print("touch")

mr = car()
mr.drive()
print("The Car is " + mr.color)

test = Airplane()
test.acc()

# The Car is balck
# The driver is Sam
# acc is already

使用issubclass()來判斷是否為子類別

1
2
print(issubclass(Airplane, car)) 
# True

方法覆寫(Method Overriding)

當子類別中定義了和父類別同名的方法(Method),這時候子類別的物件(Object)呼叫這個同名方法時,其中的實作內容將會覆蓋掉父類別的同名方法,這就叫做方法覆寫(Method Overriding)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class car:
def drive(self):
print("The driver is Sam")

# class Airplane(car):
# def acc(self):
# print("acc is already")

class buff(car):
def tes(self):
super().drive()
print("touch")

mr = car()
mr.drive()
test = buff()
test.tes()

# The driver is Sam
# The driver is Sam
# touch

多層繼承(Multi-Level Inheritance)

如果……

1
2
3
4
5
6
7
8
9
10
11
12
class car:
def drive(self):
print("The driver is Sam")

class Airplane(car):
def acc(self):
print("acc is already")

class buff(Airplane):
def tes(self):
super().drive()
print("touch")

這樣就會變得互相牽引,不過以上面為例似乎不明顯就是了

多重繼承(Multiple Inheritance)

趕鴨子上架

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class animal:
def eat(self):
print("eat fish")

class bird:
def eat(self):
print("eat bird")

class duck(animal, bird):
pass

me = duck()
me.eat()
# 這邊會出現
# eat fish
# 如果我將animal與bird的順序交換,則會出現eat bird

為了避免這個問題,我們需要將上面2個class內部修正一下

1
2
3
4
5
6
7
8
9
10
11
class animal:
def eat(self):
print("eat fish")

class bird:
def wing(self):
print("eat bird")

class duck(animal, bird):
pass
# ....

這樣就ok了喔~~