【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
Exercise 40
代码
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 reght there"])
bulls_on_parade = Song(["They really around the family",
"With pockets full of shells"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
输出
Notes
①class定义类,__init__()初始化类
②定义类、实例化类、调用相关函数与变量的方法
Exercise 41
代码
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
if len(sys.argv) == 2 and sys.argv[1] == 'english':
PHRASES_FIRST = True
else:
PHRASES_FIRST = False
# load up the words from the website
for word in urlopen(WORD_URL).readlines():
WORDS.append(word.strip())
def convert(snippet, phrases):
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, phrases:
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 parameters lists
for word in param_names:
result = result.replace("@@@", word, 1)
results.append(result)
return results
# keep going until then 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
user_answer = raw_input("> ")
print "ANSWER: %s" % answer
if user_answer == answer:
print "Congraduatons! Your answer is very right!\n\n"
else:
print "Sorry, Your answer is a little deferent frome the right answer.\n\n"
except EOFError:
print "\nBye"
输出
Notes:
①本节练习的目的是提供练习面向对象编程的概念的方法,代码中用到了循环与条件判断、字典迭代以及一些新函数
②urlopen().readlines()类似文件的readlines()方法,打开网页并读取网页内容所有行,并返回内容组成的列表
③字符串的strip()方法,用于去除字符串中的字符。需要注意,传入的参数是字符串时,会去除首尾所有在字符串内的字符。
参数为空时,删除空白符,包括" ","\n","\t","\r"
s1 = "aaabc cPython is the best bbbcaabc"
print s1.strip("abc")
print s1.strip("abc ") # abc后面有一个空格
s2 = "\n\n\tPython is the best\t\n"
print s2
print s2.strip()
该例的输出
④Python大小写转换函数:capitalize()转换首字母大写其他字母小写;upper()全部转换为大写;lower()全部转换为小写;title()全部单词首字母大写,其他字母小写
s = "python is the best!"
print s.capitalize()
print s.upper()
s = "Python is the best!"
print s.lower()
print s.title()
输出
⑤python random模块
random.sample(sequence, i) 从指定序列中随机截取指定长度的片段
random.randint(a, b) 返回一个随机数,介于a和b之间,可以取到边界值
random.shuffle(sequence) 将一个列表中的元素打乱
import random
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sample_ = random.sample(list, 5)
print sample_
for i in range(0,10):
print random.randint(1,10),
print
random.shuffle(list)
print list
该例输出
⑥字符串replace()方法
>>> s = "P***on is the best!"
>>> print s.replace("***", "yth", 1) #第一个参数是被替换字串,第二个参数是替换字串,第三个参数是最大替换次数
Python is the best!
Exercise 42
代码
## Animal is-a object (yes, sort of confusing), look at the extra credit.
class Animal(object):
pass
## Dog is-a Animal
class Dog(Animal):
def __init__(self, name):
## Dog has-a name
self.name = name
## Cat is-a Animal
class Cat(Animal):
def __init__(self, name):
## Cat has-a name
self.name = name
## Person is-a object
class Person(object):
def __init__(self, name):
## Person has-a name
self.name = name
## Person has-a pet of some kinde
self.pet = None
## Employee is-a Person
class Employee(Person):
def __init__(self, name, salary):
## hnm what is this strange magic?
super(Employee, self).__init__(name)
## Employee has-a salary
self.salary = salary
## Fish is-a object
class Fish(object):
pass
## Salmon is-a Fish
class Salmon(Fish):
pass
## Halibut is-a Fish
class Halibut(Fish):
pass
## rover is-a Dog
rover = Dog("Rover")
## satan is-a Cat
satan = Cat("Satan")
## mary is-a Person
mary = Person("Mary")
## mary has-a pet
mary.pat = satan
## frank is-a Employee
frank = Employee("Frank", 120000)
## frank has-a pet
frank.pet = rover
## flipper is-a Fish
flipper = Fish()
## crouse is-a Salmon
crouse = Salmon()
## harry is-a Halibut
harry = Halibut()
本节代码无输出
Notes:
①super()函数在类中是调用父类的函数。Python虽然支持通过直接调用父类名调用父类的方法,但缺点是更改父类名称时要遍历所以用到此父类方法的子类。super()就是为了解决这一问题。详见http://blog.csdn.net/johnsonguo/article/details/585193
②__init__(),类中定义了此方法的话,则在创建类的实例时对实例首先执行此方法,可理解为类的初始化
Exercise 44
代码
A.隐式继承(Implicit Inheritance)
class Parent(object):
def implicit(self):
print "PARENT implicit()"
class Child(Parent):
pass
dad = Parent()
son = Child()
dad.implicit()
son.implicit()
输出
Notes:
①pass是Python中创建空白代码块的办法,在前面也已经见到过pass的用处
②当在父类中定义了一个函数,在子类中没有定义时,就会发生隐式继承。也就是说,所有的子类(Child这样的类)会自动获得父类所具有的的函数的功能。
B.显式覆些(Override Explicitly)
class Parent(object):
def override(self):
print "PARENT override()"
class Child(Parent):
def override(self):
print "CHILD override()"
dad = Parent()
son = Child()
dad.override()
son.override()
输出
Notes:
①子类中定义与父类中相同名称的函数时,子类的函数会取代父类函数的功能
C. 运行前或运行后覆写
class Parent(object):
def altered(self):
print "PARENT altered()"
class Child(Parent):
def altered(self):
print "CHILD, BEFORE PARENT altered()"
super(Child, self).altered()
print "CHILD, AFTER PARENT altered()"
dad = Parent()
son = Child()
dad.altered()
son.altered()
输出
Notes
①super函数的调用
D.混合情况
class Parent(object):
def override(self):
print "PARENT override()"
def implicit(self):
print "PARENT implicit()"
def altered(self):
print "PARENT altered()"
class Child(Parent):
# override
def override(self):
print "CHILD override()"
def altered(self):
# override
print "CHILD, BEFORE PARENT altered()"
# implicit
super(Child, self).altered()
print "CHILD, AFTER PARENT altered()"
dad = Parent()
son = Child()
dad.implicit()
son.implicit()
dad.override()
son.override()
dad.altered()
son.altered()
输出
E.合成(composition)
class Other(object):
def override(self):
print "OTHER override()"
def implicit(self):
print "OTHER implicit()"
def altered(self):
print "OTHER altered()"
class Child(object):
def __init__(self):
self.other = Other()
def implicit(self):
self.other.implicit()
def override(self):
print "CHILD override()"
def altered(self):
print "CHILD, BEFORE OTHER altered()"
self.other.altered()
print "CHILD, AFTER OTHER altered()"
son = Child()
son.implicit()
son.override()
son.altered()
输出
Notes:
①作者的建议:除非必要,尽量避免多重继承这个"恶魔"
②如果有代码需要在不同场合用到,则用合成来把它们做成模块
③阅读Python风格指南
链接:英文 https://www.python.org/dev/peps/pep-0008/#copyright
中文 http://my.oschina.net/u/1433482/blog/464444
来源:oschina
链接:https://my.oschina.net/u/2297516/blog/527058