1. 程式人生 > >【Python基礎】lpthw - Exercise 40 模塊、類和對象

【Python基礎】lpthw - Exercise 40 模塊、類和對象

poc port module sin 麻煩 會有 一次 獲取 模塊

  一、 模塊(module)

  模塊中包含一些函數和變量,在其他程序中使用該模塊的內容時,需要先將模塊import進去,再使用.操作符獲取函數或變量,如

1 # This goes in mystuff.py
2 def apple():
3     print("This is an apple.")
4 
5 pear = "This is a pear."
1 import mystuff as ms
2 ms.apple()
3 
4 print(ms.pear)

  輸出為

This is an apple.
This is a pear.

  二、 類(class)

  類與模塊的比較:使用類可以重復創建很多東西出來(後面會稱之為實例化),且這些創建出來的東西之間互不幹涉。而對於模塊來說,一次導入之後,整個程序就只有這麽一份內容,更改會比較麻煩。

  一個典型的類的例子:

1 class Mystuff(object):
2 
3     def __init__(self):
4         self.tangerine = "And now a thousand years between"
5 
6     def apple(self):
7         print("I AM CLASSY APPLES!
")

  註意體會其中的object、__init__和self。

  三、 對象(object)

  對象是類的實例化,類的實例化方法就是像函數一樣調用一個類。

1 thing = Mystuff()    # 類的實例化
2 thing.apple()
3 print(thing.tangerine)

  詳解類的實例化過程:

  1. python查找Mystuff()並知道了它是你定義過的一個類。
  2. python創建一個新的空對象,裏面包含了你在該類中用def指定的所有函數。
  3. 檢查用戶是否在類中創建了__init__函數,如果有,則調用這個函數,從而對新創建的空對象實現初始化
  4. 在Mystuff的__init__函數中,有一個叫self的函數,這就是python為你創建的空對象,你可以對它進行類似模塊、字典等的操作,為它設置一些變量。
  5. 此處將self.tangerine設置成了一段歌詞,這樣就初始化了該對象。
  6. 最後python將這個新建的對象賦給一個叫thing的變量,以供後面的使用。

  四、獲取某樣東西裏包含的東西

  字典、模塊和類的使用方法對比:

 1 # dict style
 2 mystuff[apple]
 3 
 4 # module style
 5 # import mystuff
 6 mystuff.apple()
 7 
 8 # class style
 9 thing = mystuff()
10 thing.apple()

  五、第一個類的例子

 1 class Song(object):
 2 
 3     def __init__(self,lyrics):
 4         self.lyrics = lyrics
 5 
 6     def sing_me_a_song(self):
 7         for line in self.lyrics:
 8             print(line)
 9 
10 happy_bday = Song(["Happy birthday to ~ you ~",
11                     "Happy birthday to ~ you ~",
12                     "Happy birthday to ~ you ~~",
13                     "Happy birthday to you ~~~"])
14 
15 bulls_on_parade = Song(["They rally around the family",
16                         "With pockets full of shells"])
17 
18 happy_bday.sing_me_a_song()
19 
20 bulls_on_parade.sing_me_a_song()

  輸出

Happy birthday to ~ you ~
Happy birthday to ~ you ~
Happy birthday to ~ you ~~
Happy birthday to you ~~~
They rally around the family
With pockets full of shells

  •   為什麽創建__init__等函數時要多加一個self變量?

  因為如果不添加self,lyrics = “blahblahblah”這樣的代碼就會有歧義,它指的既可能是實例的lyrics屬性,也可能是一個叫lyrics的局部變量。有了self.lyrics = "blahblahblah",就清楚的知道這指的是實例的屬性lyrics。

【Python基礎】lpthw - Exercise 40 模塊、類和對象