本部分学习Python代码调试和测试方法。可用的代码调试方法有:
print打印 logging记录 pdb调试/pdb.settrace() unittest单元测试等。 样例代码如下:
本部分学习Python代码调试和测试方法。可用的代码调试方法有:
print打印 logging记录 pdb调试/pdb.settrace() unittest单元测试等。 样例代码如下:
本部分练习python中的异常处理,相当于Java中的try…catch…finally,不同的是:
1.Python中的语句是try….except….finally 2.Python中有try….except…else…finally语句,期中else语句是当没有异常捕获时执行; 3.Python中主动抛出异常的语句时raise。
本部分学习用Type和metaClass动态创建类,添加属性和方法。
# 使用元类 type 可以检查对象类型,也可以动态创建一个新类
class Student(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
def do_study(self, value):
print(self.name, "is studying", value)
stu2 = Student("S-Name", 18)
print(type(stu2))
def fn(self, name):
print("Hello:", name)
MetaStu = type("MetaStu", (object,), dict(hello=fn))
meta_stu_instance = MetaStu()
meta_stu_instance.hello("Coder")
# 使用metaclass类
# 先定义metaclass,就可以创建类,最后创建实例。
# 所以,metaclass允许你创建类或者修改类。换句话说,你可以把类看成是metaclass创建出来的“实例”。
# 可以通过__new__方法动态添加属性和方法
class StudentMetaClass(type):
def __new__(cls, name, bases, attrs):
attrs['study'] = lambda self, value: self.do_study(value)
return type.__new__(cls, name, bases, attrs)
class MyStudent(Student, metaclass=StudentMetaClass):
pass
my_stu = MyStudent("OneCoder", 38)
my_stu.study("Python")
输出如下:
本部分学习Python中定制类和枚举部分。定制类其实就是类似Java中复写String,HashCode等方法,不过更灵活,可覆盖的方法更多。
本部分练习Python高级面向对象内容,主要学习__slots__和@property相关用法,详见代码:
本部分练习Python面像对象编程基础知识。练习代码如下:
本部分练习Python模块和初级面像对象相关知识。练习代码如下:
本部门练习Python函数式编程,第二部分。
本部分练习Python函数式编程。练习高阶函数、map、reduce等常用函数。
# 高级特性
# 1. 切片和列表生成器
from collections.abc import Iterable, Iterator
list_one = list(range(10))
print(list_one[:3])
print(list_one[2:7])
print(list_one[-5:-1])
# 取后5个数
print(list_one[-5:])
# 取偶数
print(list_one[:10:2])
# 取奇数
print(list_one[1:10:2])
# 字符串也可以切片
str_one = "My name is Yummy"
print(str_one[:5])
print(str_one[:10:3])
def trim_str(str):
result = str
if str[-1] == " ":
result = str[:-1]
return result
print(trim_str("Yummy ") + "!")
print(trim_str("Yummy") + "!")
# 2. 迭代
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print(key)
for v in d.values():
print(v)
for k, v in d.items():
print(k, v)
for s in "Yummy":
print(s)
print(isinstance(123, Iterable))
for i, value in enumerate(["A", "B", "C"]):
print(i, value)
for x, y in [(1, 2), (4, 6), (7, "A")]:
print(x, y)
# 测试
def findMinAndMax(param):
max, min = None, None
if param and param != []:
for v in param:
if max == None:
max = min = v
elif v > max:
max = v
elif v < min:
min = v
return (min, max)
if findMinAndMax([]) != (None, None):
print('测试失败!')
elif findMinAndMax([7]) != (7, 7):
print('测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):
print('测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
print('测试失败!')
else:
print('测试成功!')
# 3. 列表生成
list_two = [x * x for x in range(1, 11)]
print(list_two)
list_three = [x * x for x in range(1, 11) if x % 2 != 0]
print(list_three)
list_four = [m + n for m in "ABC" for n in "123"]
print(list_four)
d_str = {"A": "1", "B": "2", "C": "3"}
list_five = [k + "=" + v for k, v in d_str.items()]
print(list_five)
# 变成小写
print([v.lower() for v in list_five])
list_six = [x * x if x % 2 == 0 else -x for x in range(1, 11)]
print(list_six)
# 练习变小写,需要判断类型
L1 = ['Hello', 'World', 18, 'Apple', None]
L_output = [x.lower() if isinstance(x, str) else x for x in L1]
print(L_output)
# 4. 生成器
g = (x * x if x % 2 == 0 else -x for x in range(1, 11))
next(g)
print(next(g))
for v in g:
print(v)
def feb(max):
a, b, n = 0, 1, 0
while n < max:
a, b = b, a + b
yield a
n += 1
return "over"
fg = feb(10)
for v in fg:
print(v)
# 练习:生成器,杨辉三角形
# 1
# / \
# 1 1
# / \ / \
# 1 2 1
# / \ / \ / \
# 1 3 3 1
# / \ / \ / \ / \
# 1 4 6 4 1
# / \ / \ / \ / \ / \
# 1 5 10 10 5 1
def g_triangle():
last_row = [1]
cur_row = [1]
n = 0
while n < 10:
if n == 0:
cur_row = [1]
elif n == 1:
cur_row = [1, 1]
else:
idx = 1
while idx < n:
cur_row.append(last_row[idx - 1] + last_row[idx])
idx += 1
cur_row.append(1)
yield cur_row
last_row = cur_row
cur_row = [1]
n += 1
return
n = 0
results = []
for t in g_triangle():
results.append(t)
n = n + 1
if n == 10:
break
for t in results:
print(t)
if results == [
[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1],
[1, 5, 10, 10, 5, 1],
[1, 6, 15, 20, 15, 6, 1],
[1, 7, 21, 35, 35, 21, 7, 1],
[1, 8, 28, 56, 70, 56, 28, 8, 1],
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
]:
print('测试通过!')
else:
print('测试失败!')
#5. 迭代器 可以被next()函数调用并不断返回下一个值的对象称为迭代器
print(isinstance((x for x in range(10)), Iterator))
print(isinstance((x for x in range(10)), Iterable))
print(isinstance([], Iterator))
print(isinstance([], Iterable))