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

Learn Python The Hard Way学习(41) - 学习面向对象

2012-07-04 15:30 513 查看
这一章学习面向对象,我做的就是给出一组你想知道的单词的定义。然后给出一些语句的解释,最后是一个练习巩固你的知识。

词语练习

class:告诉python创造一个新的东西
object:两个意思:最基本的东西和任何实例化的东西。
instance:创建一个类得到的东西。
def:在类中创建一个函数。
self:在类里面的函数中使用,是实例和object能访问的变量。
inheritance:继承,一个类可以继承另一个类,像你和你的父母。
composition:一个类可以包含另外一个类,就像汽车包含轮胎。
attribute:一个属性类,通常包括变量。
is-a:表示继承关系
has-a:包含关系

通过卡片记忆这些词语,单独的词语通常没什么意义,不过我还是要先知道它们的存在。

短语练习

class x(y):创建一个类x,它继承了y类。
class x(object):def __init__(self,j):x类包含__init__函数,函数中有self和j参数。
class x(object):def m(self,j):类x包含m函数,m函数有self和j两个参数。
foo = x():设置foo为类x的实例化。
foo.m(j):通过foo调用m函数,参数是self和j。
foo.k = q:通过foo给k属性赋值为q。

上面那些x,y,m,q等等都是可以变的。

把上面这些也写到卡片上记忆。

组合练习
组合词语和句子前,我们要做下面这些准备:

拿一张短语卡,练习上面的代码。
翻过来,读句子的解释,句子里面都包含一些词语,找到对应的词语卡。
练习句子对应的词语。
反复练习。

一个阅读测试

这是一个简单的脚本可以让你用来做练习,它只做一件事,就是使用一个urllib的库去下载一个单词列表。我们把下面的代码写到opp_test.py文件中。

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 '***'."
}

PHRASE_FIRST = False
if len(sys.argv) == 2 and sys.argv[1] == "english":
PHRASE_FIRST = True

for word in urlopen(WORD_URL).readlines():
WORDS.append(word.strip())

def convert(snippet, phrase):
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[:]

# 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

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"


运行这个例子,它会尽可能准确的回答问题。

root@he-desktop:~/mystuff# python oop_test.py
class 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 english
Make 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.
>

这些句子只是用一些常用的词语表示,这些词语仅仅是变量名或者类名,没有其他的意思,不要按照字面的意思去理解随机取出的单词。

阅读更多代码
你现在基本可以读懂所有代码了,当遇到关于类的代码时,做下面这些事情:

写下类的名称,和它继承于哪个类。
列出类的函数和参数。
列出用在self上的属性。
为每个属性标注类名。

看真实的代码是为了把我们学习到的短语匹配到代码中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: