笨方法”学Python3,习题 41:学习面向对象术语
1、有哪些术语 ?
2、术语的意思是什么 ?
一、专有词汇练习
类(class):告诉 Python 创建新类型的东西
对象(object):最基本的东西或某样东西的实例
实例(instance):让 Python 创建一个类时得到的东西
def :类里面定义函数的方法
self :类的函数中,self 指代被访问的对象或实例的一个变量
继承(inheritance):一个类可以继承另一个类的特性
组合(composition):一个类可以将别的类作为它的部件构建起来
属性(attribute):类的一个属性,它来自于组合且通常为一个变量
是什么(is-a):用来描述继承关系,如“鲑鱼是一种鱼”
有什么(has-a):用来描述组合关系,如“鲑鱼有一张嘴”
二、措辞练习
class X(Y) :创建一个叫 X 的类,它是 Y 的一种,Y 为基类,X 为派生类
class X(object):def __init __(self, J):类 X 有一个 __init __ 函数,接受 self 和 J 作为参数
class X(object):def M(self, J):类 X 有一个叫 M 的函数,接受 self 和 J 作为参数
foo = X():将 foo 设为类 X 的一个实例 或 将类 X 实例化得到对象 foo
foo.M(J):从 foo 中找到 M 函数,并使用 self 和 J 参数调用它
foo.K = Q :从 foo 中获取 K 属性,并将其设为 Q
三、阅读测试
# 在使用脚本前,先学习一些脚本中的函数和方法
count 方法
作用:用于统计字符串里某个字符出现的次数,可选参数为在字符串搜索的开始与结束位置
语法:str.count(sub, start= 0,end=len(string));sub 为搜索的子字符串;start 为字符串开始搜索的位置,默认为第一个字符;end 为字符串中结束搜索的位置,默认为字符串的最后一个位置
len 函数
返回对象(字符、列表、元组等)长度或项目个数
random 方法
作用:random() 方法返回随机生成的一个实数,它在[0,1)范围内
注意:random()是不能直接访问的,需要导入 random 模块
应用:
replace 方法
作用:把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次
语法:str.replace(old, new[, max]);old 为将被替换的子字符串;new 为新字符串,用于替换old子字符串;max 为可选字符串, 替换不超过 max 次
str.encoding
作用:返回编码后的字符串,它是一个 bytes 对象
sys.argv
sys.argv 简单地说就是一个从程序外部获取参数的桥梁,在习题13中有应用
try/except 语句
作用:用来检测 try 语句块中的错误,从而让 except 语句捕获异常信息并处理
urlib.request 模块和 urlopen 函数
urllib.request: urllib.request 模块提供了最基本的构造 HTTP 或其他协议请求的方法,利用它可以模拟浏览器的一个请求发起过程
urllib.request.urlopen()函数用于实现对目标url的访问
练习
所使用的代码:
import random
from urllib.request import urlopen
import sys
WORD_URL = "http://learnpythonthehardway.org/words.txt"
WORDS = []
PHRASES = {
"class %%%(%%%):":
"Make a class named %%% that is-a %%%.",
"class %%%(object):ntdef __init__(self, ***)":
"class %%% has-a __init__ that takes self and *** params.",
"class %%%(object):ntdef ***(self, @@@)":
"class %%% has-a function *** that takes self and @@@ params.",
"*** == %%%()":
"Set *** to an instance of class %%%.",
"***.***(@@@)":
"From *** get the *** function,call it with params 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(str(word.strip(), encoding="utf-8"))
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 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 = list(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)
input(">")
print(f"ANSWER: {answer}nn")
except EOFError:
print("nBye")
---------------------------------------------------------------------------------------------------
理解整个脚本是次要的,主要要知道脚本是如何使用的即如何做脚本出的题目,例子如下:
1、运行脚本,随机出现如下结果(出现的结果是随机的题目)
2、根据input提示符输入答案,比较答案,看看自己理解的是否正确
3、也可以反向做题,给描述输入伪代码,运行脚本前需要添加参数“english”
## 如果不知道英语格式,可以根据脚本中的PHRASES字典来做题
总结:
1、知道了如下代码的意思:
- class X(Y)
- class X(object):def __init __(self, J)
- class X(object):def M(self, J)
- foo = X()
- foo.M(J)
- foo.K = Q
2、派生类是基类的一种,如桌子是家居的一种;派生类有自己的属性,如桌子有四只桌脚,但是基类没有这种属性;基类有方法,如打造家居,派生类可以运用基类的方法或函数
3、将类实例化可以得到对象,对象可以调用类的属性与函数
4、类中的函数都有一个 self 参数
^ v ^,知乎此系列文章内容均会在微信公众号中同步更新,公众号:小民有个小旮旯