python - 如何将一个类方法的值返回给同一类的其他方法
问题描述
下面是我的课程,我想将函数 add() 中的 n 和 d 的值返回给函数 simple() 以便在计算 GCD 后返回分数,我该怎么做?另外,我不能只在 simple 中调用 add 函数,因为我必须为所有其他计算添加函数 下面是代码:
class Fraction:
def __init__(self, num, denom) -> None:
self.num = num
self.denom = denom
if self.denom == 0:
raise ZeroDivisionError("cannot divide by zero")
def __add__(self, other: "Fraction") -> "Fraction":
n: int = self.num * other.denom + self.denom * other.num
d: int = self.denom * other.denom
def simplify(self) -> "Fraction":
n1: Fraction = abs(self.num)
n2: Fraction= abs(self.denom)
gcd: int = 1
k:int = 1
while k <= n1 and k <= n2:
if n1 % k == 0 and n2 % k == 0:
gcd = k
k += 1
a:int = self.num / gcd
b:int = self.denom / gcd
new = Fraction(a,b)
return new
解决方案
推荐阅读
- c# - 关系不能改变,外键不可为空
- java - DirectBuffer 加速 ImageIO
- search - NetSuite - 如何使标准项目字段可搜索
- django - Django保存多对多字段的选定值
- c# - 如何在 C# 的泛型方法中访问属性值?
- java - 如何将图像从项目目录检索到 jlabel?
- microcontroller - 带有 GSM 模块的 PIC 微控制器
- asp.net - 使用 Javascript 渲染 React JS 组件
- spring - 为什么 Spring bean 必须是可序列化的?
- python-2.x - 为什么 41 == 0041 的结果在 python 中给出 False?