1、#Eg0: 同级目录下创建宴会邀请函`
def invite():
with open('邀请函.txt',mode='w') as kitty:
kitty.write('诚挚邀请您来参加本次宴会')
print("滴~请查收您信封 /微笑")
#微笑查收可以删除,只是无聊时添加的
invite()
2、#Eg1:在上题基础上添加内容best regards、李雷
def invite():
with open('邀请函.txt',mode = 'a') as kitty:
kitty.write('\nbest regards')
kitty.write('\n李雷')
print("滴~请查收您信封 /微笑")
invite()
3、#Eg2:在上题基础上将文件分别发送给旭丁、徐美丽、韩梅梅
def invite():
names = ['旭丁', '徐美丽', '韩梅梅']
#那个题目原名是:丁一,王美丽,韩梅梅 /一样,无聊改的
with open('邀请函.txt', mode='r') as kitty:
content = kitty.read()
for name in names:
with open('%s邀请函.txt' % name, mode='w') as hello:
hello.write('%s:\n' % name)
hello.write(content)
print("滴~请查收您信封 /微笑")
invite()
4、#Eg3:假设邀请函现在的目录是D:/test/邀请函.txt,需要在D:/test/路径下的以各位收件人名字命名的文件夹下,将相应的邀请函邮件放入
def invite():
names = ['旭丁', '徐美丽', '韩梅梅']
#那个题目原名是:丁一,王美丽,韩梅梅 /一样,无聊改的
with open('邀请函.txt', mode='r') as kitty:
content = kitty.read()
for name in names:
with open('%s邀请函.txt' % name, mode='w') as hello:
hello.write('%s:\n' % name)
hello.write(content)
print("滴~请查收您信封 /微笑")
invite()
5、#Eg4:设计Bird、fish类,都继承自Animal类,实现其方法print_info(),输出信息
class Animal():
def __init__(self,age):
self.age = age
def print_info(self):
print("我今年%d岁了!" % (self.age))
class Bird(Animal):
def __init__(self, color):
super().__init__(4)
self.color = color
def print_info(self):
print("我是一只%s的鸟" % (self.color))
super().print_info()
class Fish(Animal):
def __init__(self, weight):
super().__init__(2)
self.weight = weight
def print_info(self):
print("我是一只%d斤重的鱼" % (self.weight))
super().print_info()
bird = Bird("红色")
bird.print_info()
fish = Fish(5)
fish.print_info()
6、#Eg5:设计一个简单的购房商贷月供计算器类,按照以下公式计算总利息和每月还款金额:`
class Caculator():
def __init__(self, loan, time):
self.loan = loan
if time == "1":
self.time = 3
elif time == "2":
self.time = 5
elif time == "3":
self.time = 20
def get_total_interests(self):
return self.loan * self.get_interests_rate()
def get_interests_rate(self):
if self.time == 3:
return 0.0603
elif self.time == 5:
return 0.0612
elif self.time == 20:
return 0.0639
def get_monthly_payment(self):
return (self.loan + self.get_total_interests()) / (self.time * 12)
loan = int(input("请输入贷款金额:"))
time = input("请选择贷款年限:1.3年(36个月) 2.5年(60个月) 3.20年(240个月)")
loan_caculate = Caculator(loan, time)
print("月供为:%f" % loan_caculate.get_monthly_payment())
7、#Eg6:创建一个人类Person,定义使用手机打电话的方法use_phone_call():`
class Phone():
def call(self):
print("使用功能机打电话")
class IPhone(Phone):
def call(self):
print("使用苹果手机打电话")
class APhone(Phone):
def call(self):
print("使用安卓手机打电话")
class Person():
def use_phone_call(self, phone):
phone.call()
person = Person()
person.use_phone_call(Phone())
person.use_phone_call(IPhone())
person.use_phone_call(APhone())