1. 程式人生 > >《 笨方法學 Python 》_ 習題 40

《 笨方法學 Python 》_ 習題 40

習題 40:模組、類和物件

模組是包含函式和變數的 Python 檔案,可以匯入這個檔案,可以使用 "." 操作符訪問模組中的函式和變數。

模組還可以用一種方法去理解:可以把它們當做一種特殊的字典,通過它們可以儲存一些 Python 程式碼,可以通過 "." 操作符訪問這些程式碼。Python 還有一種另外一種程式碼結構用來實現類似的目的,那就是類,通過類,你可以把一組函式和資料放到一個容器中,從而用 "." 操作符訪問類中的函式和變數。


現在有三種方法可以從某個東西里獲取東西:

# dict sytle
mystuff['apples']

# module style            呼叫模組
mystuff.apples()        # 訪問模組的函式
mystuff.tangerine       # 訪問模組的變數

# class style
thing = MyStuff()         呼叫類
thing.apples()          # 訪問類的函式
thing.tangerine         # 訪問類的變數
class Song:
    
    def __init__(self, lyrics):
        self.lyrics = lyrics
        
    def sing_me_a_song(self):
        for line in self.lyrics:
            print(line)
            
happy_bday = Song(["Happy birthday to you",            # 呼叫類
                   "I don't want to get sued",
                   "So I'll stop right there"])

bulls_on_parade = Song(["There rally around the family",
                        "With pockets full of shells"])
                        
happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()

建立 __init__ 或者別的類函式時需要多加一個 self 變數。


習題 41:學習面向物件術語


import random
import urllib.request
import sys

WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []

PHRASES = {
        "class %%%(%%%):":
        "Make a class named %%% that is-a %%%.",
        "class %%%(object):\n\tdef __init__(self, ***)":
        "class %%% has-a __init__ that takes self and *** parameters.",
        "class %%%(object):\n\tdef ***(self, @@@)":
        "class %%% has-a function mnamed *** that takes self and @@@parameters.",
        "*** = %%%()":
        "Set *** to an instance of class %%%.",
        "***.***(@@@)":
        "From *** get the *** function, and call it with parameters self, @@@.",
        "***.*** = '***'":
        "From *** get the *** attribute and set it to '***'."
}

# do they want to drill phrases first
PHRASE_FIRST = False
if len(sys.argv) == 2 and sys.argv[1] == "english":
    PHRASE_FIRST = True

# load up the words from the website
for word in urllib.request.urlopen(WORD_URL).readlines():
    WORDS.append(word.strip())

def convert(snippet, phrase):
    class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))]
    other_names = random.sample(WORDS, snippet.count("%%%"))
    results = []
    param_names = []
    
    for i in range(0, snippet.count("@@@")):
        param_count = random.randint(1, 3)
        param_names.append(', '.join(random.sample(WORDS, param_count)))
        
    for sentence in snippet, phrase:
        result = sentence[:]
        
        # fake class names
        for word in class_names:
            result = result.replace("%%%", word, 1)
            
        # fake other names
        for word in other_names:
            result = result.replace("***", word, 1)
            
        #fake parameter lists
        for word in param_names:
            result = result.replace("@@@", word, 1)
            
        results.append(result)
        
    return results
    
# keep going until they hit CTRL-D
try:
    while True:
        snippets = list(PHRASES.keys())
        random.shuffle(snippets)
        
        for snippet in snippets:
            phrase = PHRASES[snippet]
            qusetion, answer = convert(snippet, phrase)
            if PHRASE_FIRST:
                question, answer = answer, question
                
            print(question)
            
            input("> ")
            print("ANSWER: %s\n\n" % answer)
except EOFError:
    print("\nBye")

程式執行出現錯誤,尚未解決。

result = sentence[:]
# Python 中複製列表的的方法,使用"列表切片"語法 [:] 對列表中的所有元素進行切片操作
習題 42:物件、類及從屬關係
## Animal is-a object
class Animal:
    pass

## Dog is-a Animal    
class Dog(Animal):
    def __init__(self, name):
        self.name = name

## Cat is-a Animal
class Cat(Animal):
    def __init__(self, name):
        self.name = name

## Person is-a object        
class Person:
    def __init__(self, name):
        self.name = name
        self.pet = None
    
## Employee is-a Person
class Employee(Person):
    def __init__(self, name, salary):
        super(Employee, self).__init__(name)
        self.salary = salary

## Fish is-a object
class Fish:
    pass

## Salmon is-a Fish    
class Salmon(Fish):
    pass

## Halibut is-a Fish
class Halibut(Fish):
    pass

## rover is-a Dog    
rover = Dog("Rover")

## satan is-a Cat
satan = Cat("Satan")

## mary is-a Person
mary = Person("Mary")

## mary has-a pet, satan is-a cat
mary.pet = satan

## frank is-a Employee
frank = Employee("Frank", 120000)

## frank has-a pet
frank.pet = rover

## flipper is-a Fish
flipper = Fish()

## crouse is-a Salmon
crouse = Salmon()

## harry is-a Halibut
harry = Halibut()