Programming Foundations with Python (closed)
標(biāo)簽(空格分隔): Udacity
Course Syllabus
1.1 Lesson 0: Introduction
1.2 Lesson 1: Using Functions
1.3 Lesson 2: Using Classes
1.4 Lesson 3: Making Classes
1.5 Final Project
[TOC]
Lesson 1: Using Functions
We will use functions (webbrowser.open and os.rename) from the Python Standard Library to build two projects in this lesson. After that we will present a scenario where using functions will not present a very elegant solution; this will illuminate the need for a new programming tool called Classes.
必須要import
才能調(diào)用function.圖中是一個能打開browser的命令。

1.1 Making the Program Wait
time.sleep()
里存放的是seconds,如果想用2 hours,就這么用time.sleep(2*60*60)

1.2 Adding a Loop
每隔10s來一個break,一共三次break。
在shell里import time
后,可以直接調(diào)用time.ctime()
來查看當(dāng)前時間。
ctrl+c
可在shell里終止當(dāng)前程序

1.3 Where Does Webbrowser Come From?

1.4 Secret Message
1.4.1 程序描述
把一堆圖片文件名更改,得到圖片中透露的secret message.
比如一開始是亂序的,每隔文件名都有數(shù)字,我們要寫一個program把這些數(shù)字去除

執(zhí)行remove program

發(fā)現(xiàn)所有文件名中的數(shù)字都沒有了

得到排好序的圖片文件

1.4.2 procedure(Planning a Secret Message)
- Get file names
- For each file:
rename it

1.4.3 step 1: Opening a File(Get file names)


好了,step 1 is done.
至于為什么要在
"C:\OOP\prank"
前加r
?參考這個答案的第一第二個答案,貼兩張圖在這里如果懶得看原文的話。


在linux下,只是文件路徑不一樣而已
import os
file_list = os.listdir(r"/home/xu/Pictures/prank")
print file_list
1.4.4 step 2: Changing_Filenames(For each file: rename it)
先要解決一個小問題,怎么把文件名中的數(shù)字去除?
用translate()
:
#Following is the syntax for translate() method ?
str.translate(table[, deletechars]);
'''
Parameters:
table -- You can use the maketrans() helper function in the string module to create a translation table.
deletechars -- The list of characters to be removed from the source string.
'''

用os.rename()
來更換名字
rename(src, dst)
#Rename the file or directory source to dstination.
寫好了程序

但是在運行后出現(xiàn)了錯誤

這是怎么回事?
因為當(dāng)前的path并不是存放圖片文件的path。用
os.getcwd()
來獲得當(dāng)前work directry.
解決方法,用
os.chdir()
來更改當(dāng)前directy.
一個小貼士,在執(zhí)行更改每個文件名的操作前,把就文件名和新文件名都打印出來,這樣更直觀。不然就算運行成果,沒有error,也不會有什么提示。

1.4.5 ename Troubles——Exception
當(dāng)遇到下面兩種情況時,會有error發(fā)生,這種error叫做Exception。關(guān)于這個之后再具體介紹

1.4.6 rename_files()的完整code
import os
def rename_files():
# (1)get files name from a folder
file_list = os.listdir("/home/xu/Pictures/prank")
# (2) for each file, rename filename
os.chdir("/home/xu/Pictures/prank")
for file_name in file_list:
os.rename(file_name, file_name.translate(None, "0123456789"))
# 以上程序已經(jīng)完成了rename的功能,但是這些程序并不完善,有很多可以優(yōu)化的地方,以下是改進版
import os
def rename_files():
# (1)get files name from a folder
file_list = os.listdir("/home/xu/Pictures/prank")
#print file_list # this is a list of string containing the file name
saved_path = os.getcwd()
print ("Current Working Directory is " + saved_path) # python 3中是print(),最好加上
os.chdir("/home/xu/Pictures/prank")
# (2) for each file, rename filename
for file_name in file_list:
print ("Old Name - " + file_name)
print ("New Name - " + file_name.translate(None, "01234556789"))
os.rename(file_name, file_name.translate(None, "0123456789"))
os.chdir(saved_path) # 運行完程序后,再把目錄變回原先的地址
1.5 When Functions Do Not Suffice
我們的目標(biāo)是做一個網(wǎng)站,用一個程序顯示一部電影的trailer和info。
1.5.1 方法一:function:movies.py
比如下面的movies.py
:

但是這種方法要導(dǎo)入的參數(shù)太多,不推薦。
1.5.2 方法二:用Template
寫一個template,然后每一步電影都用這個template。這樣就可以在調(diào)用function的時候不用添加過多參數(shù)

但是這種方法要給每一個電影都寫一個.py文件,而且一旦template里做了更改,其他電影.py
文件里也要一個個修改,這種方法很不效率。
1.5.3 方法三:class
理想的效果是,我們用一個template,但不寫multiple files. 而toy_story 和avatar are the tpye of template.為了實現(xiàn)這種效果,我們要使用class,這部分內(nèi)容在lesson 2.

Lesson 2: Using Classes
2.1 Lesson 2a(Using Classes): Draw Turtles
本節(jié)課的目標(biāo)是 Drawing Turtles

2.1.1 Drawing a Square

import turtle #這個是python里用來畫graph的包
def draw_square():
# we need a red carpet as the background
window = turtle.Screen() # window 代表carpet
window.bgcolor("red")
brad = turtle.Turtle() # grab the turtle funciton,brad是圖像中的指針
brad.forward(100) # the distence we want to move forward
window.exitonclick() # 功能:當(dāng)點擊圖像時,會自動關(guān)閉。要是沒有的話無法關(guān)閉圖像所在窗口
draw_square()
因為我們要得到一個squre,所以畫線要進行四次,每次轉(zhuǎn)90度。
import turtle
def draw_square():
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.forward(100)
brad.right(90) # 轉(zhuǎn)90度
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
window.exitonclick()
draw_square()
2.1.2 Change Turtle Shape, Color, and Speed
import turtle
def draw_square():
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("yellow")
brad.speed(2)
brad.forward(100)
brad.right(90) # 轉(zhuǎn)90度
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
window.exitonclick()
draw_square()
相關(guān)文檔
效果圖

2.1.3 Where Does Turtle Come From?
python的標(biāo)準(zhǔn)庫里有很多module

其中的tutle
里有一個class,叫Turtle
。而我們通過brad = turtle.Turtle()
創(chuàng)建了brad。這個brad的類型就是class的name:Turtle
. 所以這個brad
就像Turtle
一樣,可以通過brad.forward()
這樣直接調(diào)用function。

2.1.4 Two Turtles

效果圖

2.4.5 Improving Code Quality

這段代碼是不好的
- 里面沒有用loop來畫squre
- function的名字是
draw_square()
,但是第二個圖用angie.curcle()
畫了個圓,沒有邏輯性。
修改版

2.4.6 What Is a Class?
In summation, you can think a class
as a blueprint, its objects
as example or instances of that blueprint

2.4.7 Making a Circle out of Squares
import turtle #這個是python里用來畫graph的包
def draw_square(turtle):
for i in range(1, 5):
turtle.forward(100)
turtle.right(90)
def draw_art():
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("yellow")
brad.speed(2)
for i in range(1, 37):
draw_square(brad)
brad.right(10)
window.exitonclick()
draw_art()
效果圖

2.4.8 They Look So Similar(function and class)
當(dāng)我們在call webbwroser.open()
時,沒什么大不了的,只是在call a function.
但是黨我們在call turtle.Turtle()
時,it in turn called the __init_()
function, which create or initialized space in memory that didn't exist before.

2.2 Lesson 2b(Using Classes): Send Text
2.2.1 Twilio
Our goal is using code to send a message to your phone.
要實現(xiàn)這一功能,需要一個python 標(biāo)準(zhǔn)庫以外的一個lib,叫Twilio
。只不過這個庫并不支持日本的短信服務(wù)。
這個頁面是Udacity教怎么Download Twilio.
2.2.2 Setting Up Our Code
from twilio.rest import TwilioRestClient
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "AC32a3c49700934481addd5ce1659f04d2"
auth_token = "{{ auth_token }}"
client = TwilioRestClient(account_sid, auth_token)
message = client.messages.create(body="Jenny please?! I love you <3",
to="+14159352345", # Replace with your phone number
from_="+14158141829") # Replace with your Twilio number
print message.sid
2.2.3 Python Keyword From
在twilio
這個floder下,有rest
這個floder,在rest這個folder中有__init__.py
這個文件,在init.py中有TwilioRestClient
這個class。


case 1:
from twilio.rest import TwilioRestClient
client = TwilioRestClient(account_sid, auth_token)
case 2:
from twilio import rest
client = rest.TwilioRestClient(account_sid, auth_token)
2.2.4 Where Does Twilio Come From?

we use the rest.TwilioRestClient
to create a instace, and call this instace client
. we could do something to this instance, like send SMSes, etc. 其實我們是用TwilioRestClient
這個class中的__init__()
來creat sapce,創(chuàng)建新的instance叫clent
.

2.2.5 Connecting Turtle and Twilio


2.3 Lesson 2c(Using Classes): Profanity Editor
通過一個program來檢測document里是否有curse word
2.3.1 Planning Profanity Editor
one way to do

2.3.2 Reading from a File
the movie_quotes.txt
file:
-- Houston, we have a problem. (Apollo 13)
-- Mama always said, life is like a box of chocolates. You never know what you are going to get. (Forrest Gump)
-- You cant handle the truth. (A Few Good Men)
-- I believe everything and I believe nothing. (A Shot in the Dark)
read code
def read_text():
quotes = open("/home/xu/Desktop/movie_quotes.txt")
contents_of_file = quotes.read()
print(contents_of_file)
quotes.close()
read_text()
執(zhí)行后就能得到movie_quotes.txt
中的文本
但是其中的open()
是從哪里來的呢?
2.3.3 Where Does Open Come From?
使用open()
時不用import
任何東西,因為open()
is used so commenly, so it always avilable. These functions are called built-in funcitons

2.3.4 Connecting Turtle and Open

2.3.5 Checking for Curse Words
這個google 提供的網(wǎng)站可以檢測是否是curse words。而我們可以利用這個網(wǎng)站來幫我們檢測,不用自己準(zhǔn)備語料庫對比。
如果把url中的shot改為shit,返回就會時true
.

2.3.6 Accessing a Website with Code
connection = urllib.urlopen("http://www.wdyl.com/profanity?q=" + text_to_check) # 把文本傳給url

如果文本里有curse words,返回true.

2.3.7 Place Urllib and Urlopen

2.3.8 Printing a Better Output

2.3.9 Connecting Turtle, Open, and Urllib

Lesson 3: Making Classes
3.1 Lesson 3a(Making Classes): Movie Website
我們的goal是建一個下面一樣的Movie Website,收集你喜歡的movie。點擊圖片后,會播放trailer。

3.1.1 What Should Class Movie Remember?
class movie 和我們之間創(chuàng)建的幾個class是同一種類型.下圖是class design:

那么,在class movie
中,我們想讓它記住關(guān)于電影的哪些信息呢?

可以實現(xiàn)的functions,舉例

想讓class movie實現(xiàn)的functions:
除了記住一些數(shù)據(jù)外,還想讓class movie實現(xiàn)播放trailer的功能。

3.1.2 Defining Class Movie
Google Python Style Guide這個是google寫的關(guān)于python代碼規(guī)范的文檔。里面提到了怎么命名(naming)。關(guān)于classname, the first character should be upper case. So we use class Movie
rather than class movie
我們在同一個folder movie下創(chuàng)建了兩個.py文件,一個是media.py
,另一個是entertainment_center.py
. 規(guī)范的用法,在一個文件里定義class,在另一個文件里通過import這個class來使用它。

現(xiàn)在我們想要搞清楚的是,執(zhí)行toy_story = media.Movie()
時到底發(fā)生了什么。這個和我們之前用的brad = turtle.Turtle()
一樣。雖然之前提到過,但這次我們要理清楚。
3.1.3 Where Does Class Movie Fit?

call toy_story = media.Movie()
的時候,我們創(chuàng)建了一個instance,叫toy_story
, class Media
里的__init__()
叫做constructor,因為它construc the new space and memry for the new instance.

要分清這幾個名詞

3.1.4 Defining __init__
要注意__init__()
中的underscore。 These underscores are a way for Python to tell us, the name init, is essentially reserved in Python, and that, this is a special function or method. What's special about init? Is that, it initializes or creates space in memory.



為了實現(xiàn)右上角幾個要初始化的值,我們要somehow someway 去初始化圖中的代碼。
we want init, to initialize pieces of information like title, story line, and others that we want to remember inside our class. Here's a way to do that. self.title, self.storyline, self.poster_image_url and self.trailer_youtube_url
. Now, we have to somehow initialize these variables, with information init is going to receive. And in particular, it's going to receive, four pieces of information.

在__init__()
的括號里,直接導(dǎo)入?yún)?shù),把這些參數(shù)賦給self.xxxx
就完成了初始化。

media.py
里的內(nèi)容:
class Movie():
def __init__(self, movie_title, movie_storyline, poster_image,
trailer_youtube):
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
但我們在entertainment_center.py
中運行
import media
toy_story = media.Movie()
會得到錯誤,因為沒有導(dǎo)入?yún)?shù)。所以要在加上參數(shù)才行。
import media
toy_story = media.Movie("Toy Story",
"A story of a boy and his toys that come to life",
"http://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg",
"https://www.youtube.com/watch?v=vwyZH85NQC4")
print (toy_story.storyline)
3.1.5 What Is Going On Behind the Scenes

3.1.5 the Avatar
我們再添加一部電影——Avatar

3.1.6 Behind the Scenes
Avatar 的示意圖。Now, once init gets called and all of these four arguments receive their appropriate values, all of the variables that are associated with the instance avatar, they get initialized appropriately.

Here is our class Movie. And after defining the class Movie, I created two of its instances, toy_story and avatar. I could have created more instances, but for now, I've just created these two.
Now, when I created these two instances, what I was really doing behind the scenes, is I was setting aside space for each instance. And within that space, each instance had their own copy of variables. These variables include title, storyline, poster_image_url and trailer_youtube_url.
Now, because these variables are unique to each instance of class movie, these variables are called instance variables.


3.1.7 Is Self Important? (remove self)
從self.storyline = movie_storyline
中把self
去掉。在運行程序時會有error。


3.1.8 Next Up: Show_trailer
看一下我們之前的設(shè)計圖,讓class movie該記的東西都記住了,接下來要實現(xiàn)播放trailer的function.what we want to do is run a line of code like this: avatar.show_trailer()
. And when that runs, we want it to[br]play the trailer of the movie Avatar.

a function that[br]is defined inside a class and is associated with an instance[br]is called an instance method.

3.1.9 Playing Movie Trailer

然后在另一個.py
里調(diào)用剛才定義好的播放trailer的function

3.1.10 Recap Vocab
這張總結(jié)class的圖要好好理解和記憶。

3.1.11 Designing the Movie Website
設(shè)計展示movie的website
在entertainment_center.py
中添加更多的的movies

但想要turn this into a movie website, we need a piece of code that weed out.
we call this code, fresh_tomatoes.py
.

This file, fresh_tomatoes.py
, has a function inside it called, open_movies_page
. What this function does, is that it takes in, a list of movies as input, and as output it creates and opens an HTML page or a website, that shows the movies you gave it in the first place.

3.1.12 Coding the Movie Website
open_movies_page
need a list of movies.

code:
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 10 20:39:06 2015
@author: xu
"""
from media import Movie
import fresh_tomatoes
avatar = Movie('Avatar',
'A marine on an alien planet.',
'http://upload.wikimedia.org/wikipedia/id/b/b0/Avatar-Teaser-Poster.jpg',
'https://www.youtube.com/watch?v=5PSNL1qE6VY')
ghd = Movie('Groundhog Day',
'A man re-lives the same day until he gets it right.',
'http://upload.wikimedia.org/wikipedia/en/b/b1/Groundhog_Day_(movie_poster).jpg',
'https://www.youtube.com/watch?v=wE8nNUASSCo')
imitation_game = Movie('The Imitation Game',
'A man invents computer science and a computer to win a war.',
'http://upload.wikimedia.org/wikipedia/fi/a/a1/The_Imitation_Game.jpg',
'https://www.youtube.com/watch?v=S5CjKEFb-sM')
matrix = Movie('The Matrix',
'A computer hacker takes the wrong colored pill.',
'http://upload.wikimedia.org/wikipedia/en/c/c1/The_Matrix_Poster.jpg',
'https://www.youtube.com/watch?v=m8e-FF8MsqU')
wizard = Movie('The Wizard of Oz',
'Transported to sureal landscape, a young girl kills the first person she meets and then teams up with three strangers to kill again.',
'http://ia.media-imdb.com/images/M/MV5BMTU0MTA2OTIwNF5BMl5BanBnXkFtZTcwMzA0Njk3OA@@._V1_SX640_SY720_.jpg',
'https://www.youtube.com/watch?v=VNugTWHnSfw')
live = Movie('Live Nude Girls',
'A chick flick (without nudity) yet named to make it easier to get your boyfriend to watch it with you.',
'http://upload.wikimedia.org/wikipedia/en/5/53/Live_nude_girls.jpg',
'https://www.youtube.com/watch?v=8vXCajxxPcY')
#creates a list of the movies defined above and launches the web site.
movies = [avatar, ghd, imitation_game, matrix, live, wizard]
fresh_tomatoes.open_movies_page(movies)
效果圖

總結(jié)一下整個流程

最左側(cè)的html文件是我們在運行了程序后自動產(chǎn)生的。

3.2 Lesson 3b(Making Classes): Advanced Topics
本3.2節(jié)的內(nèi)容是為了介紹Advanced Ideas in OOP。
3.2.1 Class Variables
之前我們介紹過instance varibables, 這些是在def的function里的. 每個instance有自己的 variables, 互相不能共享。


Sometimes however, we need variables that we want all of our instances to share. So consider the variable valid ratings for a movie。比如電影的評分,這個每部電影都有的東西就不用在每個instance里單獨創(chuàng)建,互相共享的話會更方便。
而我們這次要介紹的是 class variables, 這些定義在def 的函數(shù)之外。也就是說創(chuàng)建的所有instance都能使用這些class variables.

我們在class movie 所在的media.py
中添加class variables. 推薦全用大寫。
the value of this variable valid_strings is probably a constant, that the value of this variable is probably not going change every now and then. When we define a constant like this, the Google Style Guide for Python recommends that we use all caps or an upper case to define a variable like that.

注意在entertainment_center.py
文件的最后,我們是如何call class variables的。

結(jié)果圖

3.2.2 Doc Strings
class中有很多有underscore的Attributes. 比如__doc__
就是。只要在文檔里用"""xxxxxxx"""
包住的注釋部分,都能用module_name.class_name.__doc__
調(diào)用。

在media.py
中添加了""" xxxxxx """
注釋的部分,在entertainment_center.py
文件中最后用media.Movie.__doc__
來調(diào)用

執(zhí)行后效果

3.2.3 Using Predefined Class Variables
除了__doc__
之外,class中一般還有其他的Predefined variables。
Predefined Class Attributes,具體可見這個網(wǎng)站

測試效果圖。__name__
是class name, __module__
是存放這個class的module name, 即media.py
中的media。

3.2.4 Inheritance
這個inheritance的概念在OOP中很重要。如其字面的意思child可以從parent那里繼承很多共性。

3.2.5 Class Parent
在inheritance.py
中定義class parent

3.2.6 Class Child
注意代碼中升級到inheritance的部分
class Child(Parent)
把繼承的class放入括號中.
Parent.__init__(self, last_name, eye_color)
在__init__
內(nèi)部,initialize the parent.

那么,quiz!執(zhí)行后輸出的結(jié)果順序是怎樣的?

兩個class內(nèi)都有print語句用來判斷輸出的順序,由此可知程序執(zhí)行的順序。

那么,如何利用inheritance來update class movie?
3.2.7 Updating the Design for Class Movie

3.2.8 Reusing Methods
怎么通過inheritance利用methods?
在class parent中定義了show_info()
,那么只要class child繼承了parent,即使在class child中不定義show_info()
也能直接使用。

運行效果

3.2.9 Method Overriding
緊跟上一小節(jié),如果在class child中再重新命名一個show_info()
的function,那么這個新的function就會把從parent那里繼承來的show_info()
overriding掉。調(diào)用的時候只會使用class child中定義的show_info()
function,而不是class parent中的function.

4 Final Project
對整個project介紹的很詳細(xì)