Learn Python the Hard Way Ex41记录

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]//第n个参数为sys.argv[n]

strip(): 用于删除首尾特定字符

strip(s [,chars]) -> 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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值