python之面向对象(基础篇)
面向对象是什么
在了解面向对象之前,先展示一段代码:
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print(line)
#实例化
happy_bday = Song(["Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"])
bulls_on_parade = Song(["There rally around the family",
"With pockets full of shells"])
#调用
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
面向对象就是将一些具有类似属性的事物抽象成一个一个的类,通过继承、多态、封装的形式去使用他们。
在这里存在一个问题:为什么创建__init__或者别的类函数时需要多加一个self变量?
答:如果不加self, cheese = 'Frank'这样的代码就存在歧义,它指的即可能是实例的cheese属性,也可能是一个叫cheese的局部变量。有了sel.cheese = 'Frank'就清楚地知道指的是实例属性self.cheese.
面向对象的专有词汇
- 类(class): 告诉python创建新类型的东西
- 对象 (object) : 两个意思,即最基本的东西,或者某样东西的实例
- 实例 (instance) : 这是让python创建一个类时得到的东西
- def : 这是在类里面定义的函数的方法
- self : 在类的函数中,self指代被访问的对象或者实例的一个变量
- 继承 (inheritance) :指一个类可以继承另一个类的特性,和父子关系类似。
- 组合(composition): 指一个类可以将别的类作为它的部件构建起来,有点像车子和车轮的关系
- 属性(attribue): 类的一个属性,它来自于组合,而且通常是一个变量
- 是什么( is-a ): 用来描述继承关系,如Salmon is-a Fish.
- 有什么( 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的函数,它接收 self 和 J 作为参数
- foo = X() : 将foo设为类X的一个实例。
- foo.M(J) : 从foo中找到M的函数,并使用 self 和 J 参数调用它。
- foo.K = Q : 从foo中获取到K属性,并将其设置为Q.
一段测试面向对象基础的代码
import random
from urllib.request 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 *** params",
"class %%%(object):\n\tdef ***(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 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}\n\n")
except EOFError:
print("\nBye")

浙公网安备 33010602011771号