面向对象编程练习
- 设计一个简单的购房商贷月供计算器类,按照以下公式计算总利息和每月还款金额:
总利息=贷款金额*利率
每月还款金额 = (贷款金额+总利息)/贷款年限
贷款年限不同利率也不同,这里规定只有如表8-2所示的3种年限、利率。
年限 |
利率 |
3年(36个月) |
6.03% |
5年(60个月) |
6.12% |
20年(240个月) |
4.39% |
class LoanCaculator():
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 = LoanCaculator(loan, time)
print("月供为:%f" % loan_caculate.get_monthly_payment())
- 设计Bird、fish类,都继承自Animal类,实现其方法print_info(),输出信息。
class Animal:
def __init__(self,age):
self.age = age
def print_info(self):
print(f'我今年{self.age}岁了!')
class bird(Animal):
def __init__(self,age,type):
self.type = type
super().__init__(age)
def print_info(self):
print(f'我是一只{self.type}的鸟')
super().print_info()
class fish(Animal):
def __init__(self,age,type):
self.type = type
super().__init__(age)
def print_info(self):
print(f'我是一只{self.type}的鱼')
super().print_info()
Bird = bird(4,"红色")
Fish = fish(2,"5斤重")
Bird.print_info()
Fish.print_info()
- 法call()。创建两个子类:苹果手机类iPhone和Android手机类APhone,并在各自类中重写方法call。创建一个人类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())