您的位置:首页 > 编程语言 > Python开发

Learn Python the Hard Way Ex41记录

2016-02-17 16:50 579 查看
http://learnpythonthehardway.org/book/ex41.html

这一章就是弄清楚定义的形式和内容意义的逻辑对应关系。

词汇:

class
: 告诉Python创建一个新的对象

object
: 两个意思:最基本类型的对象,以及某对象的任一实例

instance
: 当你让Python创建一个类时,你所获得的(实例)

def
: 用于在类中定义一个函数

self
: 在类包含的函数中,
self
是用来联系实例/对象的变量

inheritance
: 这个概念是指一个类能继承另一个类的特性,就像你和你父母的关系

composition
: 这个概念是指一个类可以由其它类组成,类似于车有轮子

attribute
: 组成类的类所具有的属性,通常是变量

is-a
: 这个短语用来形容某物继承于另一个,类似于“salmon”is-a “fish”

has-a
: 这个短语用来形容某物由其它东西组成,或包含某些特性,类似于“a salmon has-a mouth.”

短语:

-
class X(Y)


“Make a class named X that is-a Y.”

-
class X(object): def __init__(self, J)


“class X has-a
__init__
that takes self and J parameters.”

-
class X(object): def M(self, J)


“class X has-a function named M that takes self and J parameters.”

-
foo = X()


“Set foo to an instance of class X.”//将foo值置为类X的实例

-
foo.M(J)


“From foo get the M function, and call it with parameters self, J.”

-
foo.K = Q


“From foo get the K attribute and set it to Q.”//从foo访问K属性,并将Q赋值给它

对应关系练习代码:

# -- coding: utf-8 --
import random
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
PHRASES_FIRST = False
if len(sys.argv) == 2 and sys.argv[1] == "english":
PHRASES_FIRST = True

# load up the words from the website
for word in urlopen(WORD_URL).readlines():
WORDS.append(word.strip())

def convert(snippet, phrase):
# 统计snippet中“###”字符串出现的次数n,并在WORDS中随机选取n个字符串,并将字符串的首字母大写
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)
param_names.append(', '.join(random.sample(WORDS, param_count)))

for sentence in snippet, phrase:
result = sentence[:] # python中用来复制list的一种方法。将列表进行切片的语法:[:]是对列表从第一个元素到最后一个元素进行切片

# fake class names
for word in class_names:
result = result.replace("###", word, 1)

# 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 PHRASES_FIRST:
question, answer = answer, question

print question
raw_input("> ")
print "ANSWER: %s\n\n" % answer
except EOFError:
print "\nBye"


运行测试:



以上代码中所含函数:

sys.argv:

The list of command line arguments passed to a Python script.
argv[0]
is the script name (it is operating system dependent whether this is a full pathname or not).

为python中的一个list,包含从命令行中传递给脚本的参数。

使用(之前要
import sys
):

- script name:
sys.argv[0]


- 参数数量:
len(sys.argv)


- 所有参数:
str(sys.argv)


- 具体某个参数:
sys.argv
//第n个参数为sys.argv
strip(): 用于删除首尾特定字符

strip(s [,cha
4000
rs]) -> string

Return a copy of the string s with leading and trailing whitespace removed.

capitalize(s): 字面意思,字符串首字母大写

capitalize(s) -> string

Return a copy of the string s with only its first character capitalized.

sample(self, population, k):从一个特定序列中随机选择k个元素,不改变原序列

Chooses k unique random elements from a population sequence.

Returns a new list containing elements from the population while

leaving the original population unchanged. The resulting list is

in selection order so that all sub-slices will also be valid random

samples. This allows raffle winners (the sample) to be partitioned

into grand prize and second place winners (the subslices).

Members of the population need not be hashable or unique. If the

population contains repeats, then each occurrence is a possible

selection in the sample.

To choose a sample in a range of integers, use xrange as an argument.

This is especially fast and space efficient for sampling from a

large population: sample(xrange(10000000), 60)

count(s, *args): 统计字符串中s子串出现的次数

count(s, sub[, start[,end]]) -> int

Return the number of occurrences of substring sub in string

s[start:end]. Optional arguments start and end are

interpreted as in slice notation.

randint(self, a, b):

Return random integer in range [a, b], including both end points.

查找函数具体功能:

除了安装Sublime插件,在输入函数名的时候会提示函数功能之外,也可以用pydoc,或者直接上网搜ˊ_>ˋ

扩展:

python中如何对lists/arrays/tuples进行切片(slice)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python