Published 9月 23, 2018 by with 0 comment

習題40 - 模塊, 類和對象




今天練習的是class(類).
Python是一種Object Oriented Programming(OOP)物件導向式的程式語言.
這裡面有一種class的結構.
class 就像是一種藍圖或預先定義好的東西,
通過它可以創建新的迷你模塊.

目前大概只了解這樣多了~

用Notepad++打下列的程式碼,
另存為ex40.py. 我附上中文注釋方便好讀.
# 定義一個class 叫Song
class Song(object):
    
    # 定義一個函數叫lyrics(歌詞)
    def __init__(self, lyrics):
        self.lyrics = lyrics
        
    # 定義一個函數叫sing_me_a_song, 然後印出每一行
    def sing_me_a_song(self):
        for line in self.lyrics:
            print(line)

# 寫一個列表(list)            
happy_bday = Song(["Happy birthday to you",
                    "I don't want to get sued",
                    "So I'll stop right there"])

# 寫一個列表(list)                    
bulls_on_parade =  Song(["They rally around the family",
                        "With pockets full of shells"])

# 然後執行這個類代入參數(happy_bday)                    
happy_bday.sing_me_a_song()

# 然後執行這個類代入參數(bulls_on_parade)
bulls_on_parade.sing_me_a_song()

然後用Windows的cmd, 執行python.
C:\Windows\System32>cd C:\Users\Peter\Desktop\Python\LP3THW
C:\Users\Peter\Desktop\Python\LP3THW>python ex40.py
Happy birthday to you
I don't want to get sued
So I'll stop right there
They rally around the family
With pockets full of shells

C:\Users\Peter\Desktop\Python\LP3THW>

完成


最初發表 / 最後更新: 2018.09.23 / 2018.09.23

0 comments:

張貼留言