DAY 24
0

多型

``````class Animal():
def shout(self):
print('Animal shout')
class Dog(Animal):
def shout(self):
print('Dog shout')
class Cat(Animal):
def shout(self):
print('Cat shout')

d = Dog()
c = Cat()
d.shout()
c.shout()
-----------------------
Dog shout
Cat shout
``````

實例

``````import math

class Circle:                                       #圓形

def show_shape_info(self):                      #資料

def get_area(self):                             #計算

class Rectangle:                                    #矩形
def __init__(self,length,width):
self.length = length
self.width = width

def show_shape_info(self):
print('矩形長:'+str(self.length)+'寬:'+str(self.width))

def get_area(self):
return self.length * self.width

class Triangle:                                     #三角形
def __init__(self,bottom,height):
self.bottom = bottom
self.height = height

def show_shape_info(self):
print('三角形底:'+str(self.bottom)+'高:'+str(self.height))

def get_area(self):
return self.bottom * self.height / 2

c = Circle(10)                                      #建立物件
r = Rectangle(8,5)
t = Triangle(10,2)

shapes = c,r,t                                      #將物件加入元組

for i in shapes:                                    #用for迴圈顯示每一個物件的內容和面積
i.show_shape_info()
print('面積:'+str(i.get_area()))
-----------------------------------------

``````

參考資料

• 書名-Python程式設計入門 /葉難-編著
• 書名-輕鬆學Python3 /孫宏明-編著

Python 30天學習日誌30