zoukankan      html  css  js  c++  java
  • Learn Python the Hard Way

    Reference

    Zed Shaw - Learn Python the Hard Way

    Ex0: The Setup

    Windows

    Python 2, Atom, Terminal. 

    Ex1: A Good First Program

    Keyword

    1 print
    2 print "Hello World! "

    Run the file

    1 python ex1.py

    Error

    Garbled Chinese

    Possible Solutions (Unfortunately, none of them works.)

    1. Add ASCII encodings

    1 # -*- coding: utf-8 -*-

    2. decode & encode01

    1 print '中文'.decode("utf-8").encode("gb2312")
    2 print '中文'.decode("utf-8").encode("gbk")

    3. CHCP command01, 02

    1 chcp 65001

    01 关于win终端下python输出中文乱码问题

    02 Windows设置CMD命令行编码

    Ex2: Comments and Pound Characters

    Keywork

    1 #
    2 # Comments

    Q: If # is for comments, then how come # -*- coding: utf-8 -*- works? 

    A: Python still ignores that as code, but it's used as a kind of "hack" or workaround for problems with setting and detecting the format of a file. You also find a similar kind of comment for editor settings.

    Q: Why does the # in print "Hi # there." not get ignored?

    A: The # in that code is inside a string, so it will be put into the string until the ending " character is hit. These pound characters are just considered characters and aren't considered comments. 

    Ex3: Numbers and Math

    Keywords

    1 + # plus
    2 - # minus
    3 / # slash: 7 / 4 = 1; 7.0 / 4.0 = 1.75
    4 * # asterisk
    5 % # percent; modulus: X divided by Y with J remaining, The result of % is the J part. 
    6 < # less-than
    7 > # greater-than
    8 <= # less-than-equal
    9 >= # greater-than-equal

    Ex4: Variables and Names

    Ex5: More Variables and Printing

    Keywords

    1 my_eyes = 'Black'
    2 my_hair = 'Black'
    3 print "She's got %s eyes and %s hair." % (my_eyes, my_hair)

    03 String Formatting Operations

    04 python中%r和%s的区别

    Ex6: Strings and Text

    Python knows you want something to be a string when you put either " (double-quotes) or ' (single-quotes) around the text.

    Typically you'll use single-quotes for any short strings like 'a' or 'snow'. * Quoted from Ex7. 

    You simply put the formatted variables in the string, and then a % (percent) character, followed by the variable. The only catch is that if you want multiple formats in your string to print multiple variables, you need to put them inside ( ) (parenthesis) separated by , (commas). 

    Q: What is the difference between %r and %s?

    A: Use the %r for debugging, since it displays the "raw" data of the variable, but the others are used for displaying to users.

    Q: What's the point of %s and %d when you can just use %r?

    A: The %r is best for debugging, and the other formats are for actually displaying variables to users.

    Ex7: More Printing

    1 print "." * 10

    Result

    1 ..........
    1 print "Cheese", 
    2 print "Burger"
    3 
    4 print "Cheese"
    5 print "Burger"

    Result

    1 Cheese Burger
    2 
    3 Cheese
    4 Burger

    Ex8: Printing, Printing

     1 formatter = "%r %r %r %r"
     2 
     3 print formatter % (1, 2, 3, 4)
     4 print formatter % ("one", "two", "three", "four")
     5 print formatter % (True, False, False, True)
     6 print formatter % (formatter, formatter, formatter, formatter)
     7 print formatter % (
     8     "I had this thing",
     9     "That you could type up right.",
    10     "But it didn't sing.",
    11     "So I said goodnight."
    12 )

    Result

    1 C:UsersI******python_***>python ex8.py
    2 1 2 3 4
    3 'one' 'two' 'three' 'four'
    4 True False False True
    5 '%r %r %r %r' '%r %r %r %r' '%r %r %r %r' '%r %r %r %r'
    6 'I had this thing' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.'

    Q: Why does %r sometimes print things with single-quotes when I wrote them with double-quotes?

    A: Python is going to print the strings in the most efficient way it can, not replicate exactly the way you wrote them. This is perfectly fine since %r is used for debugging and inspection, so it's not necessary that it be pretty.

    Ex9: Printing, Printing, Printing

    1 months = "Jan
    Feb
    Mar
    Apr
    May
    Jun
    Jul
    Aug"
    2 
    3 print "Here are the months: ", months
    4 print "Here are the months: %r" % months

    Result

     1 Here are the months:  Jan
     2 Feb
     3 Mar
     4 Apr
     5 May
     6 Jun
     7 Jul
     8 Aug
     9 
    10 Here are the months: 'Jan
    Feb
    Mar
    Apr
    May
    Jun
    Jul
    Aug'

    Q: 为什么当我使用 来换行的时候,%r就不生效了?
    A: 这就是%r格式的工作原理;你如何输入的,它就如何打印输出。

    1 print """ # 换行
    2 There's something going on here.
    3 With the three double-quotes.
    4 We'll be able to type as much as we like.
    5 Even 4 lines if we want, or 5, or 6.
    6 """

    Ex10: What Was That? 

    Escape Sequences

    Keywords: r &

    r 让字符串中的转义字符失去转义的意义05

    1 print "	t"
    2 print r"	t"

    Result

    1     t
    2 	t

     表示将光标的位置回退到本行的开头位置06

    1 import time
    2 
    3 count_down = 10
    4 interval = 1
    5 for i in range( 0, int( count_down / interval ) + 1 ):
    6     print "
    " + "." * i + " " + str( i * 10 ) + "%"
    7     time.sleep( interval )
    8 print "
    Loaded"

    Result

     1  0%
     2 . 10%
     3 .. 20%
     4 ... 30%
     5 .... 40%
     6 ..... 50%
     7 ...... 60%
     8 ....... 70%
     9 ........ 80%
    10 ......... 90%
    11 .......... 100%
    12 
    13 Loaded

    05 python中- 用法

    06 Python中 ' ' 的实际应用

    Ex11: Asking Questions

    1 print "How old are you?", 
    2 age = raw_input()
    3 print "How tall are you?", 
    4 height = raw_input()
    5 print "How much do you weigh?", 
    6 weight = raw_input()
    7 
    8 print "So, you're %r old, %r tall and %r heavy." % (
    9     age, height, weight)

    Result

    1 How old are you? 26
    2 How tall are you? 167cm
    3 How much do you weigh? 60kg
    4 So, you're '26' old, '167cm' tall and '60kg' heavy.
    1 print "How old are you?"
    2 age = raw_input()
    3 print "How tall are you?"
    4 height = raw_input()
    5 print "How much do you weigh?"
    6 weight = raw_input()
    7 
    8 print "So, you're %r old, %r tall and %r heavy." % (
    9     age, height, weight)

    Result

    1 How old are you?
    2 38
    3 How tall are you?
    4 6'2"
    5 How much do you weigh?
    6 180lbs
    7 So, you're '38' old, '6'2"' tall and '180lbs' heavy.

    单引号需要被转义,从而防止它被识别为字符串的结尾。

    Keyword

    1 raw_input()

    input() raw_input() 这两个函数均能接收 字符串 ,但 raw_input() 直接读取控制台的输入(任何类型的输入它都可以接收)。而对于 input() ,它希望能够读取一个合法的 python 表达式,即你输入字符串的时候必须使用引号将它括起来,否则它会引发一个 SyntaxError 。

    除非对 input() 有特别需要,否则一般情况下我们都是推荐使用 raw_input() 来与用户交互。07

    在Python代码里input()方法将会改变你输入的东西,但是这个方法存在安全问题,请尽量避免使用它。

     1 >>> a = raw_input("input:")
     2 input:123
     3 >>> type(a)
     4 <type 'str'>
     5 >>> a = raw_input("input:")
     6 input:runoob
     7 >>> type(a)
     8 <type 'str'>
     9 
    10 >>> a = input("input:")
    11 input:123
    12 >>> type(a)
    13 <type 'int'>
    14 >>> a = input("input:")
    15 input:"runoob"
    16 >>> type(a)
    17 <type 'str'>
    18 >>> a = input("input:")
    19 input:runoob
    20 Traceback (most recent call last):
    21   File "<stdin>", line 1, in <module>
    22   File "<string>", line 1, in <module>
    23 NameError: name 'runoob' is not defined

    Q: 如何接收用户输入的数字,用来进行数学计算?
    A: 这略微复杂一些,你可以试试用x = int(raw_input()) 将通过raw_input()获得的字符串转化成整数。

    Q: 什么情况下我应该在输入的字符串前面加一个u, 比如 u'35'
    A: 在Python中用这种方式告诉你这是一个Unicode编码的字符串。用%s格式可以让你正常打印。

    1 >>> age = u'26'
    2 >>> print age
    3 26
    4 >>> print "%s" % age
    5 26

    07 Python raw_input() 函数

    Ex12: Prompting People

    1 name = raw_input("Name? ")

    pydoc

     1 C:UsersI******python_***>python -m pydoc raw_input
     2 Help on built-in function raw_input in module __builtin__:
     3 
     4 raw_input(...)
     5     raw_input([prompt]) -> string
     6 
     7     Read a string from standard input.  The trailing newline is stripped.
     8     If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
     9     On Unix, GNU readline is used if enabled.  The prompt string, if given,
    10     is printed without a trailing newline before reading.

    When necessary, input q to quit pydoc. 

    Ex13: Parameters, Unpacking, Variables

     1 # -*- coding: utf-8 -*-
     2 from sys import argv # 将Python的功能模块加入脚本;argv就是所谓的参数变量(argument variable)
     3 
     4 script, first, second, third = argv # 将argv进行解包(unpack),将每个参数赋予一个变量名
     5 
     6 print "The script is called: ", script
     7 print "Your first variable is: ", first
     8 print "Your second variable is: ", second
     9 print "Your third variable is: ", third
    10 
    11 fourth = raw_input("Your fourth variable is: ")

    Execution

    1 C:UsersI******python_***>python ex13.py 1st 2nd 3rd
    2 The script is called:  ex13.py
    3 Your first variable is:  1st
    4 Your second variable is:  2nd
    5 Your third variable is:  3rd
    6 Your fourth variable is: 4th

    Q: argv 和 raw_input()有什么区别?
    A: 它们的不同之处在于要求用户输入的位置不同。如果你想让用户在命令行输入你的参数,你应该使用argv.,如果你希望用户在脚本执行的过程中输入参数,那就就要用到raw_input()。
    Q: 命令行输入的参数是字符串吗?
    A: 是的,如果你需要输入数字,可以使用int()把他们转化成整数,可以参考 int(raw_input()). 

    Ex14: Prompting And Passing

    raw_input()的提示符

    1 prompt = '>'
    2 
    3 print "Do you like me?"
    4 likes = raw_input(prompt)

    Result

    1 Do you like me?
    2 >Yes

    Ex15: Reading Files

    Keywords

    1 txt = open(filename)
    2 print txt.read()
    3 txt.close()

    Ex16: Reading and Writing Files

    文件相关的各种命令(方法 / 函数)

    close -- 关闭文件。跟你编辑器的 文件->保存..一个意思。
    read -- 读取文件内容。你可以把结果赋给一个变量。
    readline -- 读取文本文件中的一行。
    truncate -- 清空文件,请谨慎使用该命令。
    write('stuff') -- 将stuff写入文件。

    'r' 是 open()函数的默认参数值。

    'w' 也是打开文件的一种模式。如果你用了这个参数,表示以写(write)模式打开文件。同样有'a'’表示追加模式,还有一些其他的修饰符。

    最重要的一个就是+, 使用它,你可以有'w+', 'r+', 和'a+'模式. 这样可以同时以读写模式打开文件。

    08 Python open() 函数

    Ex17: More Files

     1 from sys import argv
     2 from os.path import exists
     3 
     4 script, from_file, to_file = argv
     5 
     6 print "Copying from %s to %s" % (from_file, to_file)
     7 
     8 # in_file = open(from_file)
     9 # indata = in_file.read()
    10 indata = open(from_file).read() # 这样写的话,就不需要在执行关闭操作,当执行完这一行的时候,文件自动就被关闭了。
    11 
    12 print "The input file is %d bytes long" % len(indata)
    13 
    14 print "Does the output file exist? %r" % exists(to_file)
    15 print "Ready, hit RETURN to continue, CTRL-C to abort,"
    16 raw_input()
    17 
    18 out_file = open(to_file, 'w')
    19 out_file.write(indata)
    20 
    21 print "Alright, all done."
    22 
    23 out_file.close()
    24 # in_file.close()

    Ex18: Names, Variables, Code, Functions

     1 def print_two(*args):
     2     arg1, arg2 = args
     3     print "arg1: %r, arg2: %r" % (arg1, arg2)
     4 
     5 def print_two_again(arg1, arg2):
     6     print "arg1: %r, arg2: %r" % (arg1, arg2)
     7 
     8 def print_one(arg1):
     9     print "arg1: %r" % arg1
    10 
    11 def print_none():
    12     print "I got nothing."
    13 
    14 print_two("July","22nd")
    15 print_two_again("July","22nd")
    16 print_one("2018")
    17 print_none()

    函数print_two的问题是:它并不是创建函数最简单的方法。在 Python 函数中我们可以跳过整个参数解包的过程,直接使用()里边的名称作为变量名。这就是print_two_again实现的功能。

    Q: *args中的星号*是干嘛的?
    A: 它告诉Python把函数的所有参数组织一个列表放在args里。类似你之前用过的argv,只不过*args是用在函数里的。

    Ex19: Functions and Variables

     1 def cheese_and_crackers(cheese_count, boxes_of_crackers):
     2     print "You have %d cheeses!" % cheese_count
     3     print "You have %d boxes of crackers!" % boxes_of_crackers
     4     print "Man that's enough for a party!"
     5     print "Get a blanket.
    "
     6 
     7 print "We can just give the function numbers directly:"
     8 cheese_and_crackers(20, 30)
     9 
    10 print "OR, we can use variables from our script:"
    11 amount_of_cheese = 10
    12 amount_of_crackers = 50
    13 
    14 cheese_and_crackers(amount_of_cheese, amount_of_crackers)
    15 
    16 print "We can even do math inside too:"
    17 cheese_and_crackers(10 + 20, 5 + 6)
    18 
    19 print "And we can combine the two, variables and math"
    20 cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
    21 
    22 amount_of_cheese = raw_input("Tell me the amount of cheese: ")
    23 amount_of_crackers = raw_input("Tell me the amount of crackers: ")
    24 cheese_and_crackers(int(amount_of_cheese), int(amount_of_crackers))

    Result

     1 C:UsersI******python_***>python ex19.py
     2 We can just give the function numbers directly:
     3 You have 20 cheeses!
     4 You have 30 boxes of crackers!
     5 Man that's enough for a party!
     6 Get a blanket.
     7 
     8 OR, we can use variables from our script:
     9 You have 10 cheeses!
    10 You have 50 boxes of crackers!
    11 Man that's enough for a party!
    12 Get a blanket.
    13 
    14 We can even do math inside too:
    15 You have 30 cheeses!
    16 You have 11 boxes of crackers!
    17 Man that's enough for a party!
    18 Get a blanket.
    19 
    20 And we can combine the two, variables and math
    21 You have 110 cheeses!
    22 You have 1050 boxes of crackers!
    23 Man that's enough for a party!
    24 Get a blanket.
    25 
    26 Tell me the amount of cheese: 12
    27 Tell me the amount of crackers: 23
    28 You have 12 cheeses!
    29 You have 23 boxes of crackers!
    30 Man that's enough for a party!
    31 Get a blanket.

    Ex20: Functions and Files

     1 from sys import argv
     2 
     3 script, input_file = argv
     4 
     5 def print_all(f):
     6     print f.read()
     7 
     8 def rewind(f):
     9     f.seek(0)
    10 
    11 def print_a_line(line_count, f):
    12     print line_count, f.readline()
    13 
    14 current_file = open(input_file)
    15 
    16 print "First let's print the whole file:
    "
    17 
    18 print_all(current_file)
    19 
    20 print "Now let's rewind, kind of like a tape."
    21 
    22 rewind(current_file)
    23 
    24 print "Let's print three lines:"
    25 
    26 current_line = 1
    27 print_a_line(current_line, current_file)
    28 
    29 current_line = current_line + 1
    30 print_a_line(current_line, current_file)
    31 
    32 current_line += 1
    33 print_a_line(current_line, current_file)

    Result

     1 C:UsersI******python_***>python ex20.py ex17_to.txt
     2 First let's print the whole file:
     3 
     4 Today is a rainy day.
     5 We're self-studying Python at home.
     6 It's a bit challenging but really interesting.
     7 
     8 Now let's rewind, kind of like a tape.
     9 Let's print three lines:
    10 1 Today is a rainy day.
    11 
    12 2 We're self-studying Python at home.
    13 
    14 3 It's a bit challenging but really interesting.

    Keyword

    1 fileObject.seek(offset[, whence])
    2 # seek() 方法用于移动文件读取指针到指定位置。
    3 # offset -- 开始的偏移量,也就是代表需要移动偏移的字节数
    4 # whence:可选,默认值为 0。给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。
    5 # 该函数没有返回值。

    09 Python File seek() 方法

    Q: 文件中为什么有3个空行?
    A: 函数 readline() 返回一行以 结尾的文件内容, 在你调用print函数的最后增加一个逗号',',用来避免为每一行添加两个换行符

    1 def print_a_line(line_count, f):
    2     print line_count, f.readline(),

    Q: readline()怎么知道每一行的分界在哪里?
    A: readline()内部代码是扫描文件的每一个字节,直到找到一个 字符代码,然后停止阅读,并返回到此之前获得的所有内容。代码中f的责任是在每次调用readline()之后,维护“磁头”在文件中的位置,以保证继续读后面的每一行。

    Ex21: Functions Can Return Something

    1 def add(a, b):
    2     print "ADDING %d + %d" % (a, b)
    3     return a + b

    Ex22: What Do You Know So Far? 

    Ex23: Read Some Code

    Ex24: More Practice

     1 def secret_formula(started):
     2     jelly_beans = started * 500
     3     jars = jelly_beans / 1000
     4     crates = jars / 100
     5     return jelly_beans, jars, crates
     6 
     7 start_point = 10000
     8 beans, jars, crates = secret_formula(start_point)
     9 
    10 print "With a starting point of: %d" % start_point
    11 print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates)
    12 
    13 start_point = start_point / 10
    14 
    15 print "We can also do that this way:"
    16 print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)

    Ex25: Even More Practice

     1 def break_words(stuff):
     2     """This function will break up words for us."""
     3     words = stuff.split(' ') # 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则仅分隔 num 个子字符串10
     4     return words
     5 
     6 def sort_words(words):
     7     """Sorts the words."""
     8     return sorted(words) # 保留原对象,对所有可迭代的对象进行排序操作。11
     9 
    10 def print_first_word(words):
    11     """Prints the first word after popping it off."""
    12     word = words.pop(0) # 用于移除列表中的一个元素(默认最后一个元素 index = -1),并且返回该元素的值。12
    13     print word
    14 
    15 def print_last_word(words):
    16     """Prints the last word after popping it off."""
    17     word = words.pop(-1)
    18     print word
    19 
    20 def sort_sentence(sentence):
    21     """Takes in a full sentence and returns the sorted words."""
    22     words = break_words(sentence)
    23     return sort_words(words)
    24 
    25 def print_first_and_last(sentence):
    26     """Prints the first and last words of the sentence."""
    27     words = break_words(sentence)
    28     print_first_word(words)
    29     print_last_word(words)
    30 
    31 def print_first_and_last_sorted(sentence):
    32     """Sorts the words then prints the first and last one."""
    33     words = sort_sentence(sentence)
    34     print_first_word(words)
    35     print_last_word(words)

    Execution

     1 C:UsersI******python_***>python
     2 Enthought Canopy Python 2.7.13 | 64-bit | (default, Mar 30 2017, 11:20:05) [MSC v.1500 64 bit (AMD64)] on win32
     3 Type "help", "copyright", "credits" or "license" for more information.
     4 >>> import ex25
     5 >>> sentence = "All good things come to those who wait."
     6 >>> words = ex25.break_words(sentence)
     7 >>> words
     8 ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
     9 >>> sorted_words = ex25.sort_words(words)
    10 >>> sorted_words
    11 ['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
    12 >>> ex25.print_first_word(words)
    13 All
    14 >>> ex25.print_last_word(words)
    15 wait.
    16 >>> ex25.print_first_word(sorted_words)
    17 All
    18 >>> ex25.print_last_word(sorted_words)
    19 who
    20 >>> sorted_words
    21 ['come', 'good', 'things', 'those', 'to', 'wait.']
    22 >>> sorted_words = ex25.sort_sentence(sentence)
    23 >>> sorted_words
    24 ['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
    25 >>> ex25.print_first_and_last(sentence)
    26 All
    27 wait.
    28 >>> ex25.print_first_and_last_sorted(sentence)
    29 All
    30 who

    10 Python split()方法

    11 Python sorted() 函数

    12 Python List pop()方法

    Ex26: Congratulations, Take a Test! 

    Ex27: Memorizing Logic

    Ex28: Boolean Practice

    Q: 为什么"test" and "test" 返回 "test",以及1 and 1 返回 1 ,而不是 True?
    A: Python和很多语言可以返回布尔表达式中的一个操作数,而不仅仅是真或假。这意味着如果你计算False and 1 你会得到表达式的第一个操作数 (False) ,但是如果你计算True and 1的时候,你得到它的第二个操作数(1)。试一试吧。

     1 >>> (1 == 1) and 2
     2 2
     3 >>> (1 != 1) and 2
     4 False
     5 >>> (1 != 1) or 2
     6 2
     7 >>> ( 2 == 3 ) or (1 != 1)
     8 False
     9 >>> ( 2 != 3 ) or (1 == 1)
    10 True
    11 
    12 # 操作数默认真值
    13 # 布尔运算结果为真,如运算带有操作数,返回操作数,否则,返回True。
    14 # 布尔运算结果飞真,显示False。

    Q: !=和<>有什么不同吗?
    A: Python已经声明赞成使用!=而弃用<>,所以尽量使用!=吧。其他的应该没有区别了。

    Ex29: What If

    Q: +=表示什么意思?
    A: 代码x += 1x = x + 1 实现的是一样的功能,但是可以少输入一些字符。你可以称之为“增量”操作符。-= 也是相同的。

    Ex30: Else and If

    Q: 如果多个elif块为真,会怎样?
    A: Python的启动和运行只会针对第一个为真的代码块,所以你说的那种情况,只会执行第一块。

    Ex31: Making Decisions

    Ex32: Loops and Lists

    在你开始使用 for 循环之前,你需要在某个位置存放循环的结果。最好的方法是使用列表(list),顾名思义,列表就是一个按顺序存放东西的容器。

    你要做的是以 [(左方括号)开头“打开”列表,然后写下你要放入列表的东西,用逗号隔开,就跟函数的参数一样,最后用](右方括号)结束列表的定义。然后Python接收这个列表以及里边所有的内容,将其赋给一个变量。

    1 the_count = [1, 2, 3, 4, 5]
    2 fruits = ['apples', 'oranges', 'pears', 'apricots']
    3 change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
    1 elements = []
    2 
    3 for i in range(0, 6):
    4     print "Adding %d to the list." % i
    5     elements.append(i) # 在列表的末尾追加一个元素。
    6 
    7 for i in elements:
    8     print "Element was: %d" % i

    Result

    Adding 0 to the list.
    Adding 1 to the list.
    Adding 2 to the list.
    Adding 3 to the list.
    Adding 4 to the list.
    Adding 5 to the list.
    Element was: 0
    Element was: 1
    Element was: 2
    Element was: 3
    Element was: 4
    Element was: 5

    Q: 为什么for 循环可以使用一个没有定义过的变量?
    A:for循环开始的时候,就会定义这个变量, 并初始化。

    Q: 为什么for i in range(1, 3):只循环了两次?
    A: range()函数循环的次数不包括最后一个。所以range(1,3)只循环到2,这是这种循环最常用的方法。

    Ex33: While Loops

    while 循环所作的和if语句类似,也是去检查一个布尔表达式的真假,不一样的是它下面的代码片段不是只被执行一次,而是执行完后再调回到 while 所在的位置,如此重复进行,直到while表达式为False为止。

    1. 尽量少用while-loop,大部分时候for-loop是更好的选择。
    2. 重复检查你的while语句,确定你的布尔表达式最终会变成False 。
    3. 如果不确定,就在while循环的结尾打印出你测试的值。看看它的变化。

    for 循环只能对某种事物的集合做循环,而while可以进行任何种类的循环。但是,while循环很容易出错,大部分情况for循环也是一个很好的选择。

    Ex34: Accessing Elements of Lists

    Call Function in CMD

    1 >>> import ex34
    2 >>> ex34.animal(2)
    3 The 2nd animal is at 1 and is a python.

    Ex35: Branches and Functions

    Q: 你为什么用了while True?
    A: 这么写可以创建一个无限循环

    Q: exit()是干什么的?
    A: 在许多操作系统中可以使用exit(0)来中止程序,传递的数字参数表示是否遇到异常。如果使用exit(1)退出将会出现一个错误,但是用exit(0)就是正常的退出。参数部分和正常的布尔逻辑正好是相反的 (正常的布尔逻辑中 0==False) 您可以使用不同的数字来表示不同的错误结果。你也可以用exit(100)来表示一个不同于exit(2)exit(1)的错误信息。

    Ex36: Designing and Debugging

    13 Python中如何Debug

    Ex37: Symbol Reviews

    Keywords

     1 # and 逻辑与
     2 True and False == False
     3 
     4 # as with-as语句的一部分
     5 with X as Y: pass
     6 
     7 # assert 声明
     8 assert False, "Error!" 
     9 
    10 # break 停止整个循环
    11 while True: break
    12 
    13 # class 定义一个类
    14 class Person(object)
    15 
    16 # continue 停止这一次循环,但继续下一次循环
    17 while True: continue
    18 
    19 # def 定义一个函数
    20 def X(): pass
    21 
    22 # del 从字典中删除
    23 del X[Y]
    24 
    25 # elif else if条件
    26 if: X; elif: Y; else: J
    27 
    28 # else else条件
    29 if: X; elif: Y; else: J
    30 
    31 # except 如果捕获异常,执行该代码块
    32 except ValueError, e: print e
    33 
    34 # exec 将字符串作为Python代码执行
    35 exec 'print "hello"'
    36 
    37 # finally 不管是否有异常,finally代码块都执行
    38 finally: pass
    39 
    40 # for for循环
    41 for X in Y: pass
    42 
    43 # from 从某一模块中引入特定部分
    44 import X from Y
    45 
    46 # global 定义一个全局变量
    47 global X
    48 
    49 # if if条件
    50 if: X; elif: Y; else: J
    51 
    52 # import 引入一个模块到当前模块
    53 import os
    54 
    55 # in for循环的一部分 / 测试 X in Y. 
    56 for X in Y: pass / 1 in [1] == True
    57 
    58 # is 类似==,判断相等
    59 1 is 1 == True
    60 
    61 # lambda 创建一个无名函数
    62 s = lambda y: y ** y; s(3)
    63 
    64 # not 逻辑非
    65 not True == False
    66 
    67 # or 逻辑或
    68 True or False == True
    69 
    70 # pass 该代码块为空
    71 def empty(): pass
    72 
    73 # print 打印一个字符串
    74 print 'this string'
    75 
    76 # raise 代码出错时,抛出一个异常
    77 raise ValueError("No")
    78 
    79 # return 退出函数并返回一个返回值
    80 def X(): return Y
    81 
    82 # try 尝试代签代码块,有异常则进入except代码块
    83 try: pass
    84 
    85 # while while循环
    86 while X: pass
    87 
    88 # with 一个变量的别名
    89 with X as Y: pass
    90 
    91 # yield 暂停,返回给调用者
    92 def X(): yield Y; X().next()

    Data Types

     1 # True True布尔值
     2 True or False == True
     3 
     4 # False False布尔值
     5 False and Treu == False
     6 
     7 # None 表示“nothing”或者“no value”
     8 x = None
     9 
    10 # strings 字符串,储存文本信息
    11 x = "hello"
    12 
    13 # numbers 储存整数
    14 i = 100
    15 
    16 # floats 储存小数
    17 i = 10.389
    18 
    19 # lists 储存某种东西的列表
    20 j = [1, 2, 3, 4]
    21 
    22 # dicts 储存某些东西的键值对
    23 e = {'x': 1, 'y': 2}

    Escape Sequences

     1 \ #斜线
     2 ' #单引号
     3 " #双引号
     4 a #Bell
     5  #退格
     6 f #Formfeed
     7 
     #换行
     8 
     #Carriage
     9 	 #Tab键
    10 v #垂直的Tab

    String Formatting

     1 # %d 格式化整数(不包含浮点数)
     2 "%d" % 45 == '45'
     3 
     4 # %i 与%d相同
     5 "%i" % 45 == '45'
     6 
     7 # %o 8进制数字
     8 "%o" % 1000 == '1750'
     9 
    10 # %u 负数
    11 "%u" % -1000 == '-1000'
    12 
    13 # %x 小写的十六进制数字
    14 "%x" % 1000 == '3e8'
    15 
    16 # %X 大写的十六进制数字
    17 "%x" % 1000 == '3E8'
    18 
    19 # %e 小写'e'的指数标记
    20 "%e" % 1000 == '1.000000e+03'
    21  
    22 # %E 大写'e'的指数标记
    23 "%E" % 1000 == '1.000000E+03'
    24 
    25 # %f 浮点数
    26 "%f" % 10.34 == '10.340000'
    27 
    28 # %F 与%f相同
    29 "%F" % 10.34 == '10.340000'
    30 
    31 # %g %f或者%e中较短的一个
    32 "%g" % 10.34 == '10.34'
    33 
    34 # %G %F或者%E中较短的一个
    35 "%G" % 10.34 == '10.34'
    36 
    37 # %c 字符格式化
    38 "%c" % 34 == '""'
    39 
    40 # %r 类型格式化
    41 "%r" % int == "<type 'int'>"
    42 
    43 # %s 字符串格式
    44 "%s there" % 'hi' == 'hi there'
    45 
    46 # %% 表示百分号%
    47 "%g%%" % 10.34 == '10.34%'

    Operators

     1 # + 加
     2 2 + 4 == 6
     3 
     4 # - 减
     5 2 - 4 == -2
     6 
     7 # * 乘
     8 2 * 4 == 8
     9 
    10 # ** 幂乘
    11 2 ** 4 == 16
    12 
    13 # / 除
    14 2 / 4.0 == 0.5
    15 
    16 # // 整除,得到除法的商
    17 2 // 4.0 == 0.0
    18 
    19 # % 模除,返回除法的余数
    20 2 % 4 == 2
    21 
    22 # < 小于
    23 4 < 4 == False
    24 
    25 # > 大于
    26 4 > 4 == False
    27 
    28 # <= 小于等于
    29 4 <= 4 == True
    30 
    31 # >= 大于等于
    32 4 >= 4 == True
    33 
    34 # == 等于,比较操作对象是否相等
    35 4 == 5 == False
    36 
    37 # != 不等于
    38 4 != 5 == True
    39 
    40 # <> 不等于
    41 4 <> 5 == True
    42 
    43 # () 括号
    44 len('hi') == 2
    45 
    46 # [] 列表括号
    47 [1,3,4]
    48 
    49 # {} 字典括号
    50 {'x': 5, 'y': 10}
    51 
    52 # @ 装饰符
    53 @classmehod
    54 
    55 # , 逗号
    56 range(0, 10)
    57 
    58 # : 冒号
    59 def X():
    60 
    61 # . Dot
    62 self.x = 10
    63 
    64 # = 赋值等于
    65 x = 10
    66 
    67 # ; 分号
    68 print "hi"; print "there"
    69 
    70 # += 加等于
    71 x = 1; x += 2
    72 
    73 # -= 减等于
    74 x = 1; x -= 2
    75 
    76 # *= 乘等于
    77 x = 1; x *= 2
    78 
    79 # /= 除等于
    80 x = 1; x /= 2
    81 
    82 # //= 整除等于
    83 x = 1; x //= 2
    84 
    85 # %= 模除等于
    86 x = 1; x %= 2
    87 
    88 # **= 幂乘等于
    89 x = 1; x **= 2

    Ex38: Doing Things to Lists

     1 ten_things = "Apples Oranges Crows Telephone Light Suger"
     2 
     3 print "Wait there are not 10 things in that list. Let's fix that."
     4 
     5 stuff = ten_things.split(' ')
     6 more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
     7 
     8 while len(stuff) != 10:
     9     next_one = more_stuff.pop()
    10     print "Adding: ", next_one
    11     stuff.append(next_one)
    12     print "There are %d items now." % len(stuff)
    13 
    14 print "There we go: ", stuff
    15 
    16 print "Let's do some things with stuff."
    17 
    18 print stuff[1]
    19 print stuff[-1]
    20 print stuff.pop()
    21 print ' '.join(stuff)
    22 print '#'.join(stuff[3:5])

    Result

     1 C:UsersI******python_***>python ex37.py
     2 Wait there are not 10 things in that list. Let's fix that.
     3 Adding:  Boy
     4 There are 7 items now.
     5 Adding:  Girl
     6 There are 8 items now.
     7 Adding:  Banana
     8 There are 9 items now.
     9 Adding:  Corn
    10 There are 10 items now.
    11 There we go:  ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Suger', 'Boy', 'Girl', 'Banana', 'Corn']
    12 Let's do some things with stuff.
    13 Oranges
    14 Corn
    15 Corn
    16 Apples Oranges Crows Telephone Light Suger Boy Girl Banana
    17 Telephone#Light

    列表能实现什么?

    以扑克牌为例:

    1) 你有一堆有值的卡片。
    2) 这些卡片式一堆,一列,或者可以从头到尾排列这些卡片。
    3) 你可以随机的从顶部、中部或者底部取出卡片。
    4) 如果你想找到某张特殊的卡片, 你必须一张一张的检索这些卡片。

    什么情况可以使用列表?

    当你有一些有东西能匹配列表数据结构的有用特性时,使用列表:

    1) 如果你需要维护一组次序,记住,这是把次序编成列表,而不是给次序排序,列表不会帮你排序。
    2) 如果你需要根据一个随机数访问列表内容,记住,这时候基数从0开始。
    3) 如果你需要从头到尾操作列表内容,记住,这就是for循环。

    Ex39: Dictionaries, Oh Lovely Dictionaries

     1 states = {
     2     'Oregon': 'OR',
     3     'Florida': 'FL',
     4     'California': 'CA',
     5     'New York': 'NY',
     6     'Michigan': 'MI'
     7 }
     8 
     9 cities = {
    10     'CA': 'San Francisco',
    11     'MI': 'Detroit',
    12     'FL': 'Jacksonville'
    13 }
    14 
    15 cities['NY'] = 'New York'
    16 cities['OR'] = 'Portland'
    17 
    18 print '-' * 10
    19 print "NY State has: ", cities['NY']
    20 print "OR State has: ", cities['OR']
    21 
    22 print '-' * 10
    23 print "Michigan's abbreviation is: ", states['Michigan']
    24 print "Florida's abbreviation is: ", states['Florida']
    25 
    26 print '-' * 10
    27 print "Michigan has: ", cities[states['Michigan']]
    28 print "Florida has: ", cities[states['Florida']]
    29 
    30 print '-' * 10
    31 for state, abbrev in states.items():
    32     print "%s is abbreviated %s" % (state, abbrev)
    33 
    34 print '-' * 10
    35 for abbrev, city in cities.items():
    36     print "%s has the city %s" % (abbrev, city)
    37 
    38 print '-' * 10
    39 for state, abbrev in states.items():
    40     print "%s state is abbreviated %s and has city %s" % (
    41         state, abbrev, cities[abbrev])
    42 
    43 print '-' * 10
    44 state = states.get('Texas')
    45 
    46 if not state:
    47     print "Sorry, no Texas."
    48 
    49 city = cities.get('TX', 'Does Not Exist')
    50 print "The city for the state 'TX' is: %s" % city

    Result

     1 C:UsersI******python_***>python ex39.py
     2 ----------
     3 NY State has:  New York
     4 OR State has:  Portland
     5 ----------
     6 Michigan's abbreviation is:  MI
     7 Florida's abbreviation is:  FL
     8 ----------
     9 Michigan has:  Detroit
    10 Florida has:  Jacksonville
    11 ----------
    12 California is abbreviated CA
    13 Michigan is abbreviated MI
    14 New York is abbreviated NY
    15 Florida is abbreviated FL
    16 Oregon is abbreviated OR
    17 ----------
    18 FL has the city Jacksonville
    19 CA has the city San Francisco
    20 MI has the city Detroit
    21 OR has the city Portland
    22 NY has the city New York
    23 ----------
    24 California state is abbreviated CA and has city San Francisco
    25 Michigan state is abbreviated MI and has city Detroit
    26 New York state is abbreviated NY and has city New York
    27 Florida state is abbreviated FL and has city Jacksonville
    28 Oregon state is abbreviated OR and has city Portland
    29 ----------
    30 Sorry, no Texas.
    31 The city for the state 'TX' is: Does Not Exist

    字典能做什么?

    字典是另一个数据结构的例子,和列表一样,是编程中最常用的数据结构之一。字典是用来做映射或者存储你需要的键值对,这样当你需要的时候,你可以通过key来获取它的值。

    什么时候选择字典,什么时候选择列表?

    当遇到下面情况的时候,可以使用字典:
    1) 你要检索的东西是以一些标识为基础的,比如名字、地址或其他一切可以作为key的东西。
    2) 你不需要这些东西是有序的。词典通常不会有序的概念,所以你必须使用一个列表。
    3) 你想要通过key增删一个元素。
    也就是说,如果你要用一个非数字的key,使用dict,如果你需要有序的东西,使用list。

    有序字典:collections.OrderedDict

     1 def new(num_buckets=256):
     2     aMap = []
     3     for i in range(0, num_buckets):
     4         aMap.append([])
     5     return aMap
     6 
     7 def hash_key(aMap, key):
     8     return hash(key) % len(aMap)
     9 
    10 def get_bucket(aMap, key):
    11     bucket_id = hash_key(aMap, key)
    12     return aMap[bucket_id]
    13 
    14 def get_slot(aMap, key, default=None):
    15     bucket = get_bucket(aMap, key)
    16 
    17     for i, kv in enumerate(bucket):
    18         k, v = kv
    19         if key == k:
    20             return i, k, v
    21 
    22     return -1, key, default
    23 
    24 def get(aMap, key, default=None):
    25     i, k, v = get_slot(aMap, key, default=default)
    26     return v
    27 
    28 def set(aMap, key, value):
    29     bucket = get_bucket(aMap, key)
    30     i, k, v = get_slot(aMap, key)
    31 
    32     if i >= 0:
    33         bucket[1] = (key, value)
    34     else:
    35         bucket.append((key, value))
    36 
    37 def delete(aMap, key):
    38     bucket = get_bucket(aMap, key)
    39 
    40     for i in xrange(len(bucket)):
    41         k, v = bucket[i]
    42         if key == k:
    43             del bucket[i]
    44             break
    45 
    46 def list(aMap):
    47     for bucket in aMap:
    48         if bucket:
    49             for k, v in bucket:
    50                 print k, v

    Main Program

     1 import hashmap
     2 
     3 states = hashmap.new()
     4 hashmap.set(states, 'Oregon', 'OR')
     5 hashmap.set(states, 'Florida', 'FL')
     6 hashmap.set(states, 'California', 'CA')
     7 hashmap.set(states, 'New York', 'NY')
     8 hashmap.set(states, 'Michigan', 'MI')
     9 
    10 cities = hashmap.new()
    11 hashmap.set(cities, 'CA', 'San Francisco')
    12 hashmap.set(cities, 'MI', 'Detroit')
    13 hashmap.set(cities, 'FL', 'Jacksonville')
    14 
    15 hashmap.set(cities, 'NY', 'New York')
    16 hashmap.set(cities, 'OR', 'Portland')
    17 
    18 print '-' * 10
    19 print "NY State has: %s" % hashmap.get(cities, 'NY')
    20 print "OR State has: %s" % hashmap.get(cities, 'OR')
    21 
    22 print '-' * 10
    23 print "Michigan's abbreviation is: %s" % hashmap.get(states, 'Michigan')
    24 print "Florida's abbreviation is: %s" % hashmap.get(states, 'Florida')
    25 
    26 print '-' * 10
    27 print "Michigan has: %s" % hashmap.get(cities, hashmap.get(states, 'Michigan'))
    28 print "Florida has: %s" % hashmap.get(cities, hashmap.get(states, 'Florida'))
    29 
    30 print '-' * 10
    31 hashmap.list(states)
    32 
    33 print '-' * 10
    34 hashmap.list(cities)
    35 
    36 print '-' * 10
    37 state = hashmap.get(states, 'Texas')
    38 
    39 if not state:
    40     print "Sorry, no Texas."
    41 
    42 city = hashmap.get(cities, 'TX', 'Does Not Exist')
    43 print "The city for the state 'TX' is: %s" % city

    14 python中OrderedDict的使用

    Ex40: Modules, Classes, and Objects

    模块就像字典

    1) 包含一些函数和变量的Python文件
    2) 你可以导入这个文件
    3) 你可以用.操作符访问这个模块的函数和变量

     1 mystuff = {'apple': "I AM APPLES!"}
     2 print mystuff['apple']
     3 
     4 # mystuff.py
     5 def apple():
     6     print "I AM APPLES!"
     7 
     8 tangerine = "Living reflection of a dream"
     9 
    10 # Call
    11 mystuff['apple'] # get apple from dict
    12 
    13 import mystuff
    14 mystuff.apple() # get apple from the module
    15 mystuff.tangerine # same thing, it's just a variable

    在Python中有一套通用的模式:
    1) 有一个key=value模式的容器
    2) 通过key从容器中获取数据
    在字典中,key是一个字符串,写法为[key];在模块中,key是一个标识符,写法为.key;在其余的地方,他们几乎是一样的。

    类就像模块

    类的作用是组织一系列的函数和数据并将它们放在一个容器里,这样你可以通过.操作符访问到它们。

    1 class MyStuff(object):
    2 
    3     def __init__(self):
    4         self.tangerine = "And now a thousand years between"
    5 
    6     def apple(self):
    7         print "I AM CLASSY APPLES!"

    这个类就像写一个包含apple()方法的“迷你”mystuff模块一样。

    你可以使用Mystuff这个类,还可以用它来创建更多个Mystuff,而他们之间也不会互相冲突。当你导入一个模块时,你的整个项目也就只有一个这个模块。

    对象就像导入

    如果一个类就像一个迷你模块,那么类也会有一个类似import的概念,这个概念被称为实例化,这只是对创建一种更虚幻更聪明的叫法。当一个类被实例化,你就得到一个类的对象。

    实例化类的方法就是像调用函数一样调用这个类:

    1 thing = MyStuff()
    2 thing.apple()
    3 print thing.tangerine

    类和对象与模块的区别:

    1) 类是用来创建迷你模块的蓝本或定义。
    2) 实例化是如何创建这些小模块,并在同一时间将其导入。实例化仅仅是指通过类创建一个对象。
    3) 由此产生的迷你模块被称为对象,你可以将其分配给一个变量,让它开始运行。

     1 # dict style
     2 mystuff['apples']
     3 
     4 # module style
     5 mystuff.apples()
     6 print mystuff.tangerine
     7 
     8 # class style
     9 thing = MyStuff()
    10 thing.apples()
    11 print thing.tangerine

    Ex41: Learning to Speak Object Oriented

    单词解释

    class(类):告诉Python去创建一个新类型。
    object(对象):有两种意思,事物的基本类型,或者事物的实例化。
    instance(实例):你通过Python创建一个类所获得的。
    def:用来在类中定义一个函数。
    self:在一个类包含的函数中,self是一个用来访问实例或对象的变量。
    inheritance:概念,表示一个类可以继承另一个类的特征,就像你和你的父母。
    composition:概念,表示一个类可以包含其他类,就像汽车轮子。
    attribute:类所拥有的特性,通常是变量。
    is-a:惯用语,表示一个东西继承自另一个东西(a),像在“鲑鱼”是“鱼”。
    has-a:惯用语,表示由其他事情或有一个特征(a),如“鲑鱼有嘴”。

    短语解释

     1 # 创建一个叫X的类,并继承Y
     2 class X(Y)
     3 
     4 # 类X有一个__init__方法,该方法有self和J两个参数
     5 class X(object): 
     6     def __init__(self, J)
     7 
     8 # 类X有一个叫M的函数,该函数有self和J两个参数
     9 class X(object): 
    10     def M(self, J)
    11 
    12 # 给foo赋值为类X的一个实例
    13 foo = X()
    14 
    15 # 从foo里调用M函数,传递的参数为self和J
    16 foo.M(J)
    17 
    18 # 从foo里调用K属性,并将其设置为Q
    19 foo.K = Q
     1 import random
     2 
     3 WORDS = ['apple', 'pear', 'orange', 'strawberry', 'peach', 'melon']
     4 
     5 PHRASES = {
     6     "class %%%(%%%):":
     7       "Make a class named %%% that is-a %%%.",
     8     "class %%%(object):
    	def __init__(self, ***)" :
     9       "class %%% has-a __init__ that takes self and *** parameters.",
    10     "class %%%(object):
    	def ***(self, @@@)":
    11       "class %%% has-a function named *** that takes self and @@@ parameters.",
    12     "*** = %%%()":
    13       "Set *** to an instance of class %%%.",
    14     "***.***(@@@)":
    15       "From *** get the *** function, and call it with parameters self, @@@.",
    16     "***.*** = '***'":
    17       "From *** get the *** attribute and set it to '***'."
    18 }
    19 
    20 def convert(snippet, phrase):
    21     class_names = [w.capitalize() for w in # capitalize the first character of the string
    22                    random.sample(WORDS, snippet.count("%%%"))] #.sample() picks certain number of strings.. #.count("str") returns the number of str in a string
    23     other_names = random.sample(WORDS, snippet.count("***"))
    24     results = []
    25     param_names = []
    26 
    27     for i in range(0, snippet.count("@@@")):
    28         param_count = random.randint(1, 3)
    29         param_names.append(', '.join(random.sample(WORDS, param_count)))
    30 
    31     for sentence in snippet, phrase:
    32         result = sentence[:]
    33 
    34         for word in class_names:
    35             result = result.replace("%%%", word, 1)
    36 
    37         for word in other_names:
    38             result = result.replace("***", word, 1)
    39 
    40         for word in param_names:
    41             result = result.replace("@@@", word, 1)
    42 
    43         results.append(result)
    44 
    45     return results
    46 
    47 snippets = PHRASES.keys() # .keys() returns all the keys of the dictionary
    48 random.shuffle(snippets) # random.shuffle() sorts the elements randomly
    49 
    50 phrase = PHRASES["class %%%(object):
    	def ***(self, @@@)"]
    51 question, answer = convert("class %%%(object):
    	def ***(self, @@@)", phrase)
    52 if True:
    53     question, answer = answer, question
    54 
    55 print question
    56 
    57 print "ANSWER: %s
    
    " % answer

    Ex42: Is-A, Has-A, Objects, and Classes

    Super()

    15 Python super() 函数

    16 Multiple inheritance 多重继承

    Ex43: Gothons From Planet Percal #25

    自顶向下
    1) 写出或画出你的问题
    2) 从1)中提炼关键问题并搜索相关资料
    3) 为2)中的问题创建一个有层次结构的类和对象映射
    4) 编写类和测试代码,并保证他们运行
    5) 重复并精炼

    自下而上
    1) 取一小块问题,编写一些代码,并让他勉强运行
    2) 完善代码,将其转换成一些更正式的包含类和自动化测试的代码
    3) 提取其中的关键概念,并尝试找出研究他们
    4) 写出到底发生了什么的描述
    5) 继续完善代码,也可能是把它扔掉,并重新开始
    6) 移动到其他问题上,重复步骤

    17 有限状态机(FSM)

    Ex44: Inheritance Vs. Composition

    大多数继承的用途,可以简化或用组合物所取代,并应不惜一切代价避免多重继承。

    隐形继承

     1 class Parent(object):
     2 
     3     def implicit(self):
     4         print "PARENT implicit()"
     5 
     6 class Child(Parent):
     7     pass
     8 
     9 dad = Parent()
    10 son = Child()
    11 
    12 dad.implicit()
    13 son.implicit()

    Result

    1 C:UsersI******python_***>python ex44a.py
    2 PARENT implicit()
    3 PARENT implicit()

    重写方法

     1 class Parent(object):
     2 
     3     def override(self):
     4         print "PARENT override()"
     5 
     6 class Child(Parent):
     7 
     8     def override(self):
     9         print "CHILD override()"
    10 
    11 dad = Parent()
    12 son = Child()
    13 
    14 dad.override()
    15 son.override()

    Result

    1 C:UsersI******python_***>python ex44b.py
    2 PARENT override()
    3 CHILD override()

    之前或之后改变父类

     1 class Parent(object):
     2 
     3     def altered(self):
     4         print "PARENT altered()"
     5 
     6 class Child(Parent):
     7 
     8     def altered(self):
     9         print "CHILD, BEFORE PARENT altered()"
    10         super(Child, self).altered()
    11         print "CHILD, AFTER PARENT altered()"
    12 
    13 dad = Parent()
    14 son = Child()
    15 
    16 dad.altered()
    17 son.altered()

    Result

    1 C:UsersI******python_***>python ex44c.py
    2 PARENT altered()
    3 CHILD, BEFORE PARENT altered()
    4 PARENT altered()
    5 CHILD, AFTER PARENT altered()

    第10行调用了super(Child, self).altered()方法, 这个方法能够意识到继承的发生,并给你获得类Parent

    你可以这样读这行代码“调用super,参数为Childself,然后不管它返回什么,调用方法altered ”。

    super() 函数是用于调用父类(超类)的一个方法。super是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。18

    18 Python super() 函数

    包含

     1 class Other(object):
     2 
     3     def override(self):
     4         print "OTHER override()"
     5 
     6     def implicit(self):
     7         print "OTHER implicit()"
     8 
     9     def altered(self):
    10         print "OTHER altered()"
    11 
    12 class Child(object):
    13 
    14     def __init__(self):
    15         self.other = Other()
    16 
    17     def implicit(self):
    18         self.other.implicit()
    19 
    20     def override(self):
    21         print "CHILD override()"
    22 
    23     def altered(self):
    24         print "CHILD, BEFORE OTHER altered()"
    25         self.other.altered()
    26         print "CHILD, AFTER OTHER altered()"
    27 
    28 son = Child()
    29 
    30 son.implicit()
    31 son.override()
    32 son.altered()

    Result

    1 C:UsersI******python_***>python ex44e.py
    2 OTHER implicit()
    3 CHILD override()
    4 CHILD, BEFORE OTHER altered()
    5 OTHER altered()
    6 CHILD, AFTER OTHER altered()

    这段代码没有使用名字Parent,因为没有父子的is-a关系了。这是一个has-a关系,在这个关系中Child has-a Other被用来保证代码的正常工作。

    什么时候用继承,什么时候用包含?

    继承通过创建一种机制,让你在基类中有隐含的功能来解决这个问题。而包含则是通过给你的模块和函数可以在其他类别被调用来解决这个问题。

    3个指导性原则:
    1) 不惜一切代价避免多重继承,因为它太复杂太不可靠。如果你必须要使用它,那么一定要知道类的层次结构,并花时间找到每一个类是从哪里来的。
    2) 将代码封装为模块,这样就可以在许多不同的地方或情况使用。
    3) 只有当有明显相关的可重用的代码,且在一个共同概念下时,可以使用继承。

    Ex45: You Make a Game

    Ex46: A Project Skeleton

    安装包下载地址

    pip – http://pypi.python.org/pypi/pip
    distribute – http://pypi.python.org/pypi/distribute
    nose – http://pypi.python.org/pypi/nose/
    virtualenv – http://pypi.python.org/pypi/virtualenv

    解压

    执行

    1 C:UsersI******>cd Downloadspip-18.0
    2 
    3 C:UsersI******Downloadspip-18.0>python setup.py install

    其余安装方法类似。19

    创建项目骨架

     1 C:UsersI******>cd python_***
     2 
     3 C:UsersI******>python_***>mkdir projects
     4 
     5 C:UsersI******>python_***>cd projects
     6 
     7 C:UsersI******>python_***projects>mkdir skeleton
     8 
     9 C:UsersI******>python_***projects>cd skeleton
    10 
    11 C:UsersI******>python_***projectsskeleton>mkdir bin NAME tests docs
    12 
    13 C:UsersI******>python_***projectsskeleton>type nul> NAME/__init__.py
    14 
    15 C:UsersI******>python_***projectsskeleton>type nul> tests/__init__.py

    目录

    Test

    1 C:UsersI******python_***projectsskeleton>nosetests
    2 .
    3 ----------------------------------------------------------------------
    4 Ran 1 test in 0.040s
    5 
    6 OK

    使用项目骨架

    1) 拷贝这份骨架目录,把名字改成你新项目的名字。
    2) 再将NAME模组更名为你需要的名字,它可以是你项目的名字,当然别的名字也行。
    3) 编辑setup.py让它包含你新项目的相关信息。
    4) 重命名tests/NAME_tests.py,让它的名字匹配到你模组的名字。
    5) 使用nosetests检查有无错误。
    6) 开始写代码吧。

    19 windows下下载安装python、 pip、nose

    Ex47: Automated Testing

    Ex48: Advanced User Input

    Ex49: Making Sentences

    Ex50: Your First Website

    Ex51: Getting Input from a Browser

    Ex52: The Start of Your Web Game

  • 相关阅读:
    面试开发需要准备的
    多线程 多进程
    TCP/IP协议学习
    深信服算法岗实习面试经验
    TZOJ4777: 方格取数
    Python 基于 NLP 的文本分类
    mac os 使用记录
    字节跳动游戏开发岗题目
    mac进行acm(C/C++)编程
    常用的正则表达式(转)
  • 原文地址:https://www.cnblogs.com/princemay/p/9342447.html
Copyright © 2011-2022 走看看