本文是学习齐老师的《python全栈工程师》课程的笔记,欢迎学习交流。同时感谢齐老师的精彩传授!
习题01:
- 创建类SchoolKid,初始化小孩的姓名、年龄,并且有访问和修改属性的方法。然后创建类ExaggeatingKid,继承SchoolKid,子类中覆盖父类中访问年龄的方法,并将实际年龄增加2.
class SchoolKid:
def __init__(self, name, age):
self.name = name
self.age = age
def change_name(self, new_name):
self.name = new_name
return self.name
def chang_age(self, new_age):
self.age = age
return self.age
def get(self, attr='name')
if attr == 'name':
return self.name
elif attr == 'age':
return self.age
else:
print('There was not ' , attr)
return None
class ExaggeratingKid(SchoolKid):
def get(self, attr='name'):
if attr == 'name':
return self.name
elif attr == 'age':
return self.age + 2
else:
print('There was not ' , attr)
return None
习题2:
- 内置函数range的参数必须是整数。请编写一个生成器函数,以浮点数为参数(开始值,结束值,步长)生成某范围的序列。
import itertools
def frange(start, end=None, step=1.0):
if end is None:
end = float(start)
start = 0.0
assert step # 当step不为True时,抛出错误
for i in itertools.count():
nxt = start + i * step
if (step > 0.0 and nxt >= end) or (step < 0.0 and nxt <= end):
break
yield nxt
f = frange(1.2, 9)
print(list(f)) # [1.2, 2.2, 3.2, 4.2, 5.2, 6.2, 7.2, 8.2]
习题3:
- 编写一个关于矩形的对象类型,能够通过长、宽配置属性值
- 进 一步完善例题3的代码,让其使用起来更稳健。
class Rectangle:
def __init__(self):
self.width = 0
self.length = 0
def __getattr__(self, name):
if name == 'size':
return self.width, self.length
else:
raise AttributeError
def __setattr__(self, name, value):
# 此处增加了 try/except代码
try:
if name == 'size':
self.width, self.length = value
else:
self.__dict__[name] = value
except TypeError:
print('There are two numbers!')
rect = Rectangle()
rect.width = 3
rect.length = 4
print(rect.size)
print('---'*15)
rect.size = 30
print(rect.width)
print(rect.length)
运行结果:
习题4:
- 分数的表示形式如3/2这样,但是这种形式在python中是按照除法进行处理。Python的内置对象类型中又没有分数类型(不仅Python没有,是相当多高级语言都没有),所以,有必要自定义一个相关的类型。
- 附加题:在上述基础上,实现分数加法运算
class Fraction:
def __init__(self, number, denom=1):
self.number = number
self.denom = denom
def __str__(self):
return str(self.number) + '/' + str(self.denom)
__repr__ = __str__
f = Fraction(2, 3)
print(f) # 2/3
分数相加流程:
class Fraction:
def __init__(self, number, denom = 1):
self.number = number
self.denom = denom
def __str__(self):
return str(self.number) + '/' + str(self.denom)
__repr__ = __str__
@staticmethod
def gcd(a, b): # 最大公约数
if not a > b:
a, b = b, a
while b != 0:
remainder = a % b
a, b = b, remainder
return a
@staticmethod
def lcm(a, b): # 最小公倍数
return (a * b) / Fraction.gcd(a, b)
def __add__(self, other):
lcm_num = Fraction.lcm(self.denom, other.denom)
number_num = (lcm_num / self.denom * self.number ) + (lcm_num / other.denom * other.number)
return Fraction(number_num, lcm_num)
m = Fraction(1, 3)
n = Fraction(1, 2)
s = m + n
print(s)
运行结果: