Programming Foundations with Python (closed)
标签(空格分隔): 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
才能调用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
后,可以直接调用time.ctime()
来查看当前时间。
ctrl+c
可在shell里终止当前程序
1.3 Where Does Webbrowser Come From?
1.4 Secret Message
1.4.1 程序描述
把一堆图片文件名更改,得到图片中透露的secret message.
比如一开始是乱序的,每隔文件名都有数字,我们要写一个program把这些数字去除
执行remove program
发现所有文件名中的数字都没有了
得到排好序的图片文件
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)
先要解决一个小问题,怎么把文件名中的数字去除?
用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.
写好了程序
但是在运行后出现了错误
这是怎么回事?
因为当前的path并不是存放图片文件的path。用
os.getcwd()
来获得当前work directry.
解决方法,用
os.chdir()
来更改当前directy.
一个小贴士,在执行更改每个文件名的操作前,把就文件名和新文件名都打印出来,这样更直观。不然就算运行成果,没有error,也不会有什么提示。
1.4.5 ename Troubles——Exception
当遇到下面两种情况时,会有error发生,这种error叫做Exception。关于这个之后再具体介绍
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"))
# 以上程序已经完成了rename的功能,但是这些程序并不完善,有很多可以优化的地方,以下是改进版
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
我们的目标是做一个网站,用一个程序显示一部电影的trailer和info。
1.5.1 方法一:function:movies.py
比如下面的movies.py
:
但是这种方法要导入的参数太多,不推荐。
1.5.2 方法二:用Template
写一个template,然后每一步电影都用这个template。这样就可以在调用function的时候不用添加过多参数
但是这种方法要给每一个电影都写一个.py文件,而且一旦template里做了更改,其他电影.py
文件里也要一个个修改,这种方法很不效率。
1.5.3 方法三:class
理想的效果是,我们用一个template,但不写multiple files. 而toy_story 和avatar are the tpye of template.为了实现这种效果,我们要使用class,这部分内容在lesson 2.
Lesson 2: Using Classes
2.1 Lesson 2a(Using Classes): Draw Turtles
本节课的目标是 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() # 功能:当点击图像时,会自动关闭。要是没有的话无法关闭图像所在窗口
draw_square()
因为我们要得到一个squre,所以画线要进行四次,每次转90度。
import turtle
def draw_square():
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.forward(100)
brad.right(90) # 转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) # 转90度
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
window.exitonclick()
draw_square()
相关文档
- Changing Turtle's Shape
- Changing Turtle's Color
- Changing Turtle's Speed
效果图
2.1.3 Where Does Turtle Come From?
python的标准库里有很多module
其中的tutle
里有一个class,叫Turtle
。而我们通过brad = turtle.Turtle()
创建了brad。这个brad的类型就是class的name:Turtle
. 所以这个brad
就像Turtle
一样,可以通过brad.forward()
这样直接调用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)
当我们在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.
要实现这一功能,需要一个python 标准库以外的一个lib,叫Twilio
。只不过这个库并不支持日本的短信服务。
这个页面是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,创建新的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()
执行后就能得到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 提供的网站可以检测是否是curse words。而我们可以利用这个网站来帮我们检测,不用自己准备语料库对比。
如果把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 和我们之间创建的几个class是同一种类型.下图是class design:
那么,在class movie
中,我们想让它记住关于电影的哪些信息呢?
可以实现的functions,举例
想让class movie实现的functions:
除了记住一些数据外,还想让class movie实现播放trailer的功能。
3.1.2 Defining Class Movie
Google Python Style Guide这个是google写的关于python代码规范的文档。里面提到了怎么命名(naming)。关于classname, the first character should be upper case. So we use class Movie
rather than class movie
我们在同一个folder movie下创建了两个.py文件,一个是media.py
,另一个是entertainment_center.py
. 规范的用法,在一个文件里定义class,在另一个文件里通过import这个class来使用它。
现在我们想要搞清楚的是,执行toy_story = media.Movie()
时到底发生了什么。这个和我们之前用的brad = turtle.Turtle()
一样。虽然之前提到过,但这次我们要理清楚。
3.1.3 Where Does Class Movie Fit?
call toy_story = media.Movie()
的时候,我们创建了一个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.
为了实现右上角几个要初始化的值,我们要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__()
的括号里,直接导入参数,把这些参数赋给self.xxxx
就完成了初始化。
media.py
里的内容:
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()
会得到错误,因为没有导入参数。所以要在加上参数才行。
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
看一下我们之前的设计图,让class movie该记的东西都记住了,接下来要实现播放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
里调用刚才定义好的播放trailer的function
3.1.10 Recap Vocab
这张总结class的图要好好理解和记忆。
3.1.11 Designing the Movie Website
设计展示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)
效果图
总结一下整个流程
最左侧的html文件是我们在运行了程序后自动产生的。
3.2 Lesson 3b(Making Classes): Advanced Topics
本3.2节的内容是为了介绍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里单独创建,互相共享的话会更方便。
而我们这次要介绍的是 class variables, 这些定义在def 的函数之外。也就是说创建的所有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的。
结果图
3.2.2 Doc Strings
class中有很多有underscore的Attributes. 比如__doc__
就是。只要在文档里用"""xxxxxxx"""
包住的注释部分,都能用module_name.class_name.__doc__
调用。
在media.py
中添加了""" xxxxxx """
注释的部分,在entertainment_center.py
文件中最后用media.Movie.__doc__
来调用
执行后效果
3.2.3 Using Predefined Class Variables
除了__doc__
之外,class中一般还有其他的Predefined variables。
Predefined Class Attributes,具体可见这个网站
测试效果图。__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__
内部,initialize the parent.
那么,quiz!执行后输出的结果顺序是怎样的?
两个class内都有print语句用来判断输出的顺序,由此可知程序执行的顺序。
那么,如何利用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
紧跟上一小节,如果在class child中再重新命名一个show_info()
的function,那么这个新的function就会把从parent那里继承来的show_info()
overriding掉。调用的时候只会使用class child中定义的show_info()
function,而不是class parent中的function.
4 Final Project
对整个project介绍的很详细
Final Project Description
Final Project Rubric