自定义类

案例研究:用 Python 构建软件

Mark Pedigo

Principal Data Scientist

路线图

路线图:展示已完成的项目部分和即将开始的部分。

案例研究:用 Python 构建软件

每月按揭计算

每月按揭计算的公式为:

$$\text{monthly payment} = P \cdot \frac{r (1 + r)^N}{(1+r)^N - 1},$$

其中:

  • $P$ 为贷款额,
  • $r$ 为月利率,
  • $N$ 为还款月数
1 https://en.wikipedia.org/wiki/Mortgage_calculator
案例研究:用 Python 构建软件

为类添加功能

计算月供的方法

def monthly_payment(self):
    # 计算乘数
    numerator = self.monthly_interest_rate * \
        (1 + self.monthly_interest_rate) ** self.months
    denominator = (1 + self.monthly_interest_rate) ** self.months - 1
    multiplier = self.divide(numerator, denominator)
    # 计算月供
    monthly_payment = self.multiply(self.loan_amount, multiplier)
    return monthly_payment
案例研究:用 Python 构建软件

计算月供

# 实例化一个按揭计算器
mortgage_calculator = calculators.MortgageCalculator(300000, 0.065, 30)

# 计算月供
print(round(mortgage_calculator.monthly_payment, 2))
1703.37
案例研究:用 Python 构建软件

再次使用 dir()

  • dir(ClassName):列出类的函数
dir(MortgageCalculator)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', '__weakref__',
'calculate_monthly_payment', 'difference', 'monthly_interest',
'monthly_interest_rate', 'monthly_payment', 'months', 'power', 'principal',
'product', 'quotient', 'sum']
案例研究:用 Python 构建软件

F-string 示例

name = "Alice"
age = 17
# 使用 f-string 在句子中插入变量
greeting = f"Hello, my name is {name} and I'm {age} years old."
print(greeting)
Hello, my name is Alice and I'm 17 years old.
案例研究:用 Python 构建软件

让我们来练习!

案例研究:用 Python 构建软件

Preparing Video For Download...