iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 17
1
自我挑戰組

30天Python學習心得分享系列 第 17

Day 17 - 類別的定義與使用

Hi 大家好~~~
今天要來分享的是類別的定義與使用:

類別

就是封裝變數或函式(封裝的變數或函式,統稱類別的屬性)。要先定義類別,再來才能使用類別中封裝的屬性。

定義類別
class 類別名稱:
#定義封裝的變數
#定義封裝的函式

使用類別
類別名稱.屬性名稱

程式範例:

#範例 定義Test類別 
class Test:
    x=3 #定義變數
    def say(): #定義函式
        print("hello")

#範例 使用Test類別
print(Test.x+3)#取得屬性x的資料3,再+3
Test.say() #呼叫屬性say的函式

定義類別與類別屬性(封裝在類別中的變數和函式)

#定義一個類別Io,有兩個屬性,supportedSrcs和read
class Io:
    supportedSrcs=["console","file"]
    def read(src):
        print("Read from:",src)
#使用類別
print(Io.supportedSrcs)
Io.read("file")

#以下為搭配IF判斷式
class Io:
    supportedSrcs=["console","file"]
    def read(src):
        if src not in Io.supportedSrcs:
            print("Not Supported")
        else:
            print("Read from:",src)
#使用類別
print(Io.supportedSrcs)
Io.read("file")
Io.read("internet")

以上,就是今天的學習分享,
若是文章中有錯誤的地方,再麻煩前輩協助指正,謝謝大家!!!
/images/emoticon/emoticon41.gif


上一篇
Day 16 - 網路連線、公開資料串接
下一篇
Day 18 - 實體物件的建立與使用(1)
系列文
30天Python學習心得分享30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言