笨方法學Python, Lesson 40 - 44

Exercise 40python

代碼web

class Song(object):
    
    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 reght there"])
                  
bulls_on_parade = Song(["They really around the family",
                        "With pockets full of shells"])
                        
happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()

輸出shell

Notes
編程

①class定義類,__init__()初始化類api

②定義類、實例化類、調用相關函數與變量的方法app

Exercise 41 
dom

代碼ide

import random 
from urllib import urlopen
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 named *** 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
if len(sys.argv) == 2 and sys.argv[1] == 'english':
    PHRASES_FIRST = True 
else:  
    PHRASES_FIRST = False 
    
# load up the words from the website 
for word in urlopen(WORD_URL).readlines():
    WORDS.append(word.strip())
    
    
def convert(snippet, phrases):
    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, phrases:
        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 parameters lists 
        for word in param_names:
            result = result.replace("@@@", word, 1)
            
        results.append(result)
        
    return results 
    
    
# keep going until then hit CTRL^D 
try:
    while True:
        snippets = PHRASES.keys()
        random.shuffle(snippets)
        
        for snippet in snippets:
            phrase = PHRASES[snippet]
            question, answer = convert(snippet, phrase)
            if PHRASES_FIRST:
                question, answer = answer, question 
                
            print question 
            
            user_answer = raw_input("> ")
            print "ANSWER: %s" % answer 
            if user_answer == answer:
                print "Congraduatons! Your answer is very right!\n\n"
            else:
                print "Sorry, Your answer is a little deferent frome the right answer.\n\n"
except EOFError:
    print "\nBye"

輸出函數

Notes:this

①本節練習的目的是提供練習面向對象編程的概念的方法,代碼中用到了循環與條件判斷、字典迭代以及一些新函數

②urlopen().readlines()相似文件的readlines()方法,打開網頁並讀取網頁內容全部行,並返回內容組成的列表

③字符串的strip()方法,用於去除字符串中的字符。須要注意,傳入的參數是字符串時,會去除首尾全部在字符串內的字符。

參數爲空時,刪除空白符,包括" ","\n","\t","\r"

s1 = "aaabc cPython is the best bbbcaabc"
print s1.strip("abc")
print s1.strip("abc ")      # abc後面有一個空格
s2 = "\n\n\tPython is the best\t\n"
print s2
print s2.strip()

該例的輸出

④Python大小寫轉換函數:capitalize()轉換首字母大寫其餘字母小寫;upper()所有轉換爲大寫;lower()所有轉換爲小寫;title()所有單詞首字母大寫,其餘字母小寫

s = "python is the best!"
print s.capitalize()
print s.upper()
s = "Python is the best!"
print s.lower()
print s.title()

輸出

⑤python random模塊

random.sample(sequence, i)  從指定序列中隨機截取指定長度的片斷

random.randint(a, b) 返回一個隨機數,介於a和b之間,能夠取到邊界值

random.shuffle(sequence) 將一個列表中的元素打亂

import random
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]   
sample_ = random.sample(list, 5)
print sample_

for i in range(0,10):
    print random.randint(1,10),

print 
random.shuffle(list)
print list

該例輸出

⑥字符串replace()方法 

>>> s = "P***on is the best!"
>>> print s.replace("***", "yth", 1)    #第一個參數是被替換字串,第二個參數是替換字串,第三個參數是最大替換次數
Python is the best!

Exercise 42 

代碼

## Animal is-a object (yes, sort of confusing), look at the extra credit.
class Animal(object):
    pass 

## Dog is-a Animal
class Dog(Animal):
    
    def __init__(self, name):
        ## Dog has-a name 
        self.name = name 
        
##  Cat is-a Animal
class Cat(Animal):
    
    def __init__(self, name):
        ##  Cat has-a name 
        self.name = name 
        
##  Person is-a object
class Person(object):
    
    def __init__(self, name):
        ##  Person has-a name 
        self.name = name 
        
        ## Person has-a pet of some kinde 
        self.pet = None
        
##  Employee is-a Person
class Employee(Person):
    
    def __init__(self, name, salary):
        ##  hnm what is this strange magic?
        super(Employee, self).__init__(name)
        ##  Employee has-a salary
        self.salary = salary
        
##  Fish is-a object 
class Fish(object):
    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 
mary.pat = 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()

本節代碼無輸出

Notes:

①super()函數在類中是調用父類的函數。Python雖然支持經過直接調用父類名調用父類的方法,但缺點是更改父類名稱時要遍歷因此用到此父類方法的子類。super()就是爲了解決這一問題。詳見http://blog.csdn.net/johnsonguo/article/details/585193

②__init__(),類中定義了此方法的話,則在建立類的實例時對實例首先執行此方法,可理解爲類的初始化

Exercise 44

代碼

A.隱式繼承(Implicit Inheritance)

class Parent(object):
    
    def implicit(self):
        print "PARENT implicit()"
        
class Child(Parent):
    pass 
    
dad = Parent()
son = Child()

dad.implicit()
son.implicit()

輸出

Notes:

①pass是Python中建立空白代碼塊的辦法,在前面也已經見到過pass的用處

②當在父類中定義了一個函數,在子類中沒有定義時,就會發生隱式繼承。也就是說,全部的子類(Child這樣的類)會自動得到父類所具備的的函數的功能。

B.顯式覆些(Override Explicitly)

class Parent(object):
    
    def override(self):
        print "PARENT override()"
     
class Child(Parent):
    
    def override(self):
        print "CHILD override()"
        
dad = Parent()
son = Child()

dad.override()
son.override()

輸出

Notes:

①子類中定義與父類中相同名稱的函數時,子類的函數會取代父類函數的功能

C. 運行前或運行後覆寫

class Parent(object):
    
    def altered(self):
        print "PARENT altered()"
        
class Child(Parent):
    
    def altered(self):
        print "CHILD, BEFORE PARENT altered()"
        super(Child, self).altered()
        print "CHILD, AFTER PARENT altered()"
        
dad = Parent()
son = Child()

dad.altered()
son.altered()

輸出

Notes

①super函數的調用

D.混合狀況

class Parent(object):
    
    def override(self):
        print "PARENT override()"
        
    def implicit(self):
        print "PARENT implicit()"
        
    def altered(self):
        print "PARENT altered()"
        
class Child(Parent):
    
    #  override 
    def override(self):
        print "CHILD override()"
        
    def altered(self):
        # override
        print "CHILD, BEFORE PARENT altered()"
        # implicit
        super(Child, self).altered()
        print "CHILD, AFTER PARENT altered()"
        
dad = Parent()
son = Child()

dad.implicit()
son.implicit()

dad.override()
son.override()

dad.altered()
son.altered()

輸出

E.合成(composition)

class Other(object):
    
    def override(self):
        print "OTHER override()"
        
    def implicit(self):
        print "OTHER implicit()"
        
    def altered(self):
        print "OTHER altered()"
        
class Child(object):
    
    def __init__(self):
        self.other = Other()
        
    def implicit(self):
        self.other.implicit()
        
    def override(self):
        print "CHILD override()"
        
    def altered(self):
        print "CHILD, BEFORE OTHER altered()"
        self.other.altered()
        print "CHILD, AFTER OTHER altered()"
        
son = Child()

son.implicit()
son.override()
son.altered()

輸出

Notes:

①做者的建議:除非必要,儘可能避免多重繼承這個"惡魔"

②若是有代碼須要在不一樣場合用到,則用合成來把它們作成模塊

③閱讀Python風格指南

連接:英文  https://www.python.org/dev/peps/pep-0008/#copyright

中文  http://my.oschina.net/u/1433482/blog/464444

相關文章
相關標籤/搜索