对一些词语的理解:
class:告诉python创造一个新的东西
- object:两个意思:最基本的东西和任何实例化的东西。
- instance:创建一个类得到的东西。
- def:在类中创建一个函数。
- self:在类里面的函数中使用,是实例和object能访问的变量。
- inheritance:继承,一个类可以继承另一个类,像你和你的父母。
- composition:一个类可以包含另外一个类,就像汽车包含轮胎。
- attribute:一个属性类,通常包括变量。
- is-a:表示继承关系
- has-a:包含关系
对一些短句的理解:1.class X(Y): 创建一个类x,它继承了y类。
2.class X(object):def__init__(self,J):
X类包含__init__函数,函数中有self和J参数。
3.class X(object):def m(self,J):
X类包含m函数,m函数有self和J两个参数。
4.foo=X():设置foo为类X的实例化。
5. foo.M(J):通过foo调用m函数,参数是self和J。
6.foo.K=Q: 通过foo给K属性(attribute)赋值为Q
加深理解 填空():
- "Make a class named X that is-a (继承关系) Y."
- "class X has-a (包含关系)__init__ that takes self and J parameters."
- "class X has-a function named M that takes self and J parameters."
- "Set foo to an instance of class X."
- "From foo get the M function, and call it with self and parameters J."
- "From foo get the K attribute and set it to Q."
阅读测试:
import random #注释2 from urllib import urlopen import sys WORD_URL = "http://learncodethehardway.org/words.txt" WORDS = [] PHRASES = { "class %%%(%%%):": "Make a class named %%% that is-a %%%.", "class %%%(object):\n\tdef __init__(self, ***)" : "class %%% has-a __init__ that takes self and *** parameters.", "class %%%(object):\n\tdef ***(self, @@@)": "class %%% has-a function named *** that takes self and @@@ parameters.", "*** = %%%()": "Set *** to an instance of class %%%.", "***.***(@@@)": "From *** get the *** function, and call it with parameters self, @@@.", "***.*** = '***'": "From *** get the *** attribute and set it to '***'." } # do they want to drill phrases first if len(sys.argv) == 2 and sys.argv[1] == "english": PHRASE_FIRST = True else: PHRASE_FIRST = False # load up the words from the website for word in urlopen(WORD_URL).readlines(): WORDS.append(word.strip()) #注释1: def convert(snippet, phrase): ##capitalize count在注释3、4 class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))] other_names = random.sample(WORDS, snippet.count("***")) results = [] param_names = [] for i in range(0, snippet.count("@@@")): param_count = random.randint(1,3) ##注释5 param_names.append(', '.join(random.sample(WORDS, param_count))) ##注释6 sample从WORDS中随机取一个长度param_count(一个随机数)的序列,然后以‘,’为分隔符,上一步得到的所有序列 组成一个新字符串。将这个新生成的字符串赋值给param_names列表(list)?? for sentence in snippet, phrase: result = sentence[:] ##注释7 [:]是切片操作,作用取整个变量 没懂这里在干什么??收藏知乎上解释 # fake class names for word in class_names: result = result.replace("%%%", word, 1) ##注释9:Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。 # fake other names for word in other_names: result = result.replace("***", word, 1) # fake parameter lists for word in param_names: result = result.replace("@@@", word, 1) results.append(result) return results # keep going until they hit CTRL-D try: while True: snippets = PHRASES.keys() random.shuffle(snippets) #可以将列表随机打乱 for snippet in snippets: phrase = PHRASES[snippet] question, answer = convert(snippet, phrase) if PHRASE_FIRST: question, answer = answer, question print question raw_input("> ") print "ANSWER: %s\n\n" % answer except EOFError: print "\nBye"
注释:1.函数原型
声明:s为字符串,rm为要删除的字符序列
s.strip(rm) 删除s字符串中开头、结尾处,位于 rm删除序列的字符
s.lstrip(rm) 删除s字符串中开头处,位于 rm删除序列的字符
s.rstrip(rm) 删除s字符串中结尾处,位于 rm删除序列的字符
注意:
当rm为空时,默认删除空白符(包括'\n', '\r', '\t', ' ')
2.python的random模块用于生成随机数
random.sample的函数原型为:random.sample(sequence, k)
从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。
3.
str.capitalize():此方法返回的字符串只有它的第一个字符大写的副本。
eg:
str="this is a string."
print "str.capitalize(): ", %str.capitalize()
结果:
str.capitalize(): This is a string. ## 把字符串第一个字符大写
4.Python count() :用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。
str.count(sub, start=0, end=len(string))
sub -- 搜索的子字符串;
start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0;
end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
5.random.randint()的函数原型为:random.randint(a, b),用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限。
6.join(): 'sep'.join(seq)
参数说明 sep:分隔符。可以为空 seq:要连接的元素序列、字符串、元组、字典 上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串
返回值:返回一个以分隔符sep连接各个元素后生成的字符串
7.sentence其实是遍历了snippet和phrase两个数组,最后snippet和phrase都会计入sentence中。如果你run了整个程序,会发现snippet就是PHRASE中的key,phrase就是PHRASE中的value。
8.
Python的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
tup1 =('physics','chemistry',1997,2000);
tup2 =(1,2,3,4,5);
tup3 ="a","b","c","d";
9.Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
10. random.shuffle()将列表打乱。
显示:
root@he-desktop:~/mystuff# python oop_test.pyclass Deer(object):def __init__(self, connection)>ANSWER: class Deer has-a __init__ that takes self and connection parameters.class Cause(Agreement):>ANSWER: Make a class named Cause that is-a Agreement.animal.driving(arch)>ANSWER: From animal get the driving function, and call it with parameters self, arch.cat = Aftermath()>ANSWER: Set cat to an instance of class Aftermath.cork.card = 'attempt'>练习从英语到代码运行的时候在后面多加一个english的参数,运行如下:root@he-desktop:~/mystuff# python oop_test.py englishMake a class named Arm that is-a Bird.>ANSWER: class Arm(Bird):From cloud get the calculator attribute and set it to 'committee'.>ANSWER: cloud.calculator = 'committee'Set chair to an instance of class Detail.>