Programming Foundations with Python (closed)

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的命令。

pf1.png-467.7kB
pf1.png-467.7kB

1.1 Making the Program Wait

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

pf2.png-396kB
pf2.png-396kB

1.2 Adding a Loop

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

pf3.png-510.8kB
pf3.png-510.8kB

1.3 Where Does Webbrowser Come From?

pf4.png-450.7kB
pf4.png-450.7kB

1.4 Secret Message

1.4.1 程序描述

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


pf6.png-420.6kB
pf6.png-420.6kB
pf9.png-460.5kB
pf9.png-460.5kB

執(zhí)行remove program


pf7.png-512.6kB
pf7.png-512.6kB

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


pf8.png-419.2kB
pf8.png-419.2kB

得到排好序的圖片文件
pf10.png-460.5kB
pf10.png-460.5kB

1.4.2 procedure(Planning a Secret Message)

  1. Get file names
  2. For each file:
    rename it
pf11.png-187.3kB
pf11.png-187.3kB

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

pf12.png-422.7kB
pf12.png-422.7kB

pf13.png-464.5kB
pf13.png-464.5kB

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

pf15.png-80.6kB
pf15.png-80.6kB

在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.
'''
pf16.png-208.1kB
pf16.png-208.1kB

os.rename()來更換名字

rename(src, dst)
#Rename the file or directory source to dstination. 

寫好了程序

pf17.png-290.7kB
pf17.png-290.7kB

但是在運行后出現(xiàn)了錯誤
pf18.png-472.7kB
pf18.png-472.7kB

這是怎么回事?
因為當(dāng)前的path并不是存放圖片文件的path。用os.getcwd()來獲得當(dāng)前work directry.
pf19.png-433.1kB
pf19.png-433.1kB

解決方法,用os.chdir()來更改當(dāng)前directy.
pf20.png-366.3kB
pf20.png-366.3kB

一個小貼士,在執(zhí)行更改每個文件名的操作前,把就文件名和新文件名都打印出來,這樣更直觀。不然就算運行成果,沒有error,也不會有什么提示。
pf21.png-505.6kB
pf21.png-505.6kB

1.4.5 ename Troubles——Exception

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

pf22.png-113.7kB
pf22.png-113.7kB

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:

pf23.png-283.2kB
pf23.png-283.2kB

但是這種方法要導(dǎo)入的參數(shù)太多,不推薦。

1.5.2 方法二:用Template

寫一個template,然后每一步電影都用這個template。這樣就可以在調(diào)用function的時候不用添加過多參數(shù)

pf24.png-256.1kB
pf24.png-256.1kB

但是這種方法要給每一個電影都寫一個.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.


pf25.png-283.5kB
pf25.png-283.5kB

Lesson 2: Using Classes

2.1 Lesson 2a(Using Classes): Draw Turtles

本節(jié)課的目標(biāo)是 Drawing Turtles


pf26.png-285.7kB
pf26.png-285.7kB

2.1.1 Drawing a Square

pf27.png-220.4kB
pf27.png-220.4kB
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)文檔

  1. Changing Turtle's Shape
  2. Changing Turtle's Color
  3. Changing Turtle's Speed

效果圖


pf28.png-196.3kB
pf28.png-196.3kB

2.1.3 Where Does Turtle Come From?

python的標(biāo)準(zhǔn)庫里有很多module

pf29.png-480.7kB
pf29.png-480.7kB

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

pf30.png-436.1kB
pf30.png-436.1kB

2.1.4 Two Turtles

pf31.png-315.6kB
pf31.png-315.6kB

效果圖

pf32.png-192.2kB
pf32.png-192.2kB

2.4.5 Improving Code Quality

pf33.png-456.8kB
pf33.png-456.8kB

這段代碼是不好的

  1. 里面沒有用loop來畫squre
  2. function的名字是draw_square(),但是第二個圖用angie.curcle()畫了個圓,沒有邏輯性。

修改版


pf34.png-309.9kB
pf34.png-309.9kB

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

pf35.png-212.6kB
pf35.png-212.6kB

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()        

效果圖

pf36.png-178.5kB
pf36.png-178.5kB

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.

pf38.png-537kB
pf38.png-537kB

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。

pf39.png-298.3kB
pf39.png-298.3kB
pf40.png-484.7kB
pf40.png-484.7kB

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?

pf41.png-528.7kB
pf41.png-528.7kB

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.

pf42.png-526.1kB
pf42.png-526.1kB

2.2.5 Connecting Turtle and Twilio

pf43.png-193.1kB
pf43.png-193.1kB
pf44.png-202.4kB
pf44.png-202.4kB

2.3 Lesson 2c(Using Classes): Profanity Editor

通過一個program來檢測document里是否有curse word

2.3.1 Planning Profanity Editor

one way to do


pf45.png-407.2kB
pf45.png-407.2kB

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

pf46.png-421.4kB
pf46.png-421.4kB

2.3.4 Connecting Turtle and Open

pf47.png-337.7kB
pf47.png-337.7kB

2.3.5 Checking for Curse Words

這個google 提供的網(wǎng)站可以檢測是否是curse words。而我們可以利用這個網(wǎng)站來幫我們檢測,不用自己準(zhǔn)備語料庫對比。

如果把url中的shot改為shit,返回就會時true.

pf48.png-29.1kB
pf48.png-29.1kB

2.3.6 Accessing a Website with Code

connection = urllib.urlopen("http://www.wdyl.com/profanity?q=" + text_to_check)   # 把文本傳給url
pf49.png-397.2kB
pf49.png-397.2kB

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


pf50.png-394.5kB
pf50.png-394.5kB

2.3.7 Place Urllib and Urlopen

pf51.png-402.5kB
pf51.png-402.5kB

2.3.8 Printing a Better Output

pf52.png-457.7kB
pf52.png-457.7kB

2.3.9 Connecting Turtle, Open, and Urllib

pf53.png-229.4kB
pf53.png-229.4kB

Lesson 3: Making Classes

3.1 Lesson 3a(Making Classes): Movie Website

我們的goal是建一個下面一樣的Movie Website,收集你喜歡的movie。點擊圖片后,會播放trailer。

pf54.png-535kB
pf54.png-535kB

3.1.1 What Should Class Movie Remember?

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

pf55.png-206kB
pf55.png-206kB

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

pf56.png-236.6kB
pf56.png-236.6kB

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

pf57.png-190kB
pf57.png-190kB

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

pf58.png-178.9kB
pf58.png-178.9kB

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來使用它。

pf59.png-215kB
pf59.png-215kB

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

3.1.3 Where Does Class Movie Fit?

pf60.png-550.4kB
pf60.png-550.4kB

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

pf61.png-531.7kB
pf61.png-531.7kB

要分清這幾個名詞

pf62.png-520.7kB
pf62.png-520.7kB

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.

pf63.png-306.3kB
pf63.png-306.3kB
pf64.png-237.1kB
pf64.png-237.1kB
pf65.png-271kB
pf65.png-271kB

為了實現(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.

pf66.png-221.6kB
pf66.png-221.6kB

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

pf67.png-247.8kB
pf67.png-247.8kB

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

pf68.png-472.4kB
pf68.png-472.4kB

3.1.5 the Avatar

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

pf69.png-473.1kB
pf69.png-473.1kB

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.

pf71.png-447kB
pf71.png-447kB

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.

pf72.png-489kB
pf72.png-489kB
pf73.png-531.7kB
pf73.png-531.7kB

3.1.7 Is Self Important? (remove self)

self.storyline = movie_storyline 中把self去掉。在運行程序時會有error。

pf74.png-498.5kB
pf74.png-498.5kB
pf75.png-570.5kB
pf75.png-570.5kB

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.

pf76.png-211kB
pf76.png-211kB

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

pf77.png-279.6kB
pf77.png-279.6kB

3.1.9 Playing Movie Trailer

pf78.png-348.2kB
pf78.png-348.2kB

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

pf79.png-460.8kB
pf79.png-460.8kB

3.1.10 Recap Vocab

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

pf80.png-226.7kB
pf80.png-226.7kB

3.1.11 Designing the Movie Website

設(shè)計展示movie的website

entertainment_center.py中添加更多的的movies

pf81.png-191.1kB
pf81.png-191.1kB

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

pf82.png-105.9kB
pf82.png-105.9kB

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.

pf83.png-110.7kB
pf83.png-110.7kB

3.1.12 Coding the Movie Website

open_movies_page need a list of movies.

pf84.png-631.9kB
pf84.png-631.9kB

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)

效果圖

pf85.png-584.6kB
pf85.png-584.6kB

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

pf86.png-112.3kB
pf86.png-112.3kB

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

pf87.png-272.7kB
pf87.png-272.7kB

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, 互相不能共享。

pf88.png-572.8kB
pf88.png-572.8kB
pf89.png-360.2kB
pf89.png-360.2kB

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.

pf90.png-122.3kB
pf90.png-122.3kB

我們在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.

pf91.png-459.4kB
pf91.png-459.4kB

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

pf92.png-570.8kB
pf92.png-570.8kB

結(jié)果圖


pf93.png-424.2kB
pf93.png-424.2kB

3.2.2 Doc Strings

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

pf94.png-247.4kB
pf94.png-247.4kB

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

pf95.png-558.9kB
pf95.png-558.9kB

執(zhí)行后效果

pf96.png-363.1kB
pf96.png-363.1kB

3.2.3 Using Predefined Class Variables

除了__doc__之外,class中一般還有其他的Predefined variables。

Predefined Class Attributes,具體可見這個網(wǎng)站

pf97.png-46kB
pf97.png-46kB

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

pf98.png-45.7kB
pf98.png-45.7kB

3.2.4 Inheritance

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

pf99.png-228.1kB
pf99.png-228.1kB

3.2.5 Class Parent

inheritance.py中定義class parent

pf100.png-375.5kB
pf100.png-375.5kB

3.2.6 Class Child

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

pf101.png-361.2kB
pf101.png-361.2kB

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

pf102.png-360.1kB
pf102.png-360.1kB

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

pf103.png-379.5kB
pf103.png-379.5kB

那么,如何利用inheritance來update class movie?

3.2.7 Updating the Design for Class Movie

pf104.png-309.5kB
pf104.png-309.5kB

3.2.8 Reusing Methods

怎么通過inheritance利用methods?

在class parent中定義了show_info(),那么只要class child繼承了parent,即使在class child中不定義show_info()也能直接使用。

pf105.png-352.4kB
pf105.png-352.4kB

運行效果

pf106.png-352.7kB
pf106.png-352.7kB

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.

pf108.png-401.8kB
pf108.png-401.8kB

4 Final Project

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

Final Project Description

Final Project Rubric

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,501評論 6 544
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,673評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,610評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,939評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 72,668評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 56,004評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,001評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,173評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,705評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,426評論 3 359
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,656評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,139評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,833評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,247評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,580評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,371評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 48,621評論 2 380

推薦閱讀更多精彩內(nèi)容