python - 如何在名为 Fraction 的类中使用 __mul__
问题描述
如何使乘法与我的班级一起工作Fraction
?
class Fraction(object):
def __init__(self, num, den):
self.num = num
self.den = den
def resolve(self):
#a = 2
#b = 6
#c = 2
#d = 5
self.num = self.num / other.num
self.den = self.den / other.den
return self
def __str__(self):
return "%d/%d" %(self.num, self.den)
def __mul__(self, other):
den = self.den * other.num
num = self.num * other.den
return (Fraction(self.num * other.num, self.den * other.den))
print('Multiplication:', Fraction.__mul__(2, 6))
这是输出:
Traceback (most recent call last):
File "app.py", line 43, in <module>
print('Multiplication:', Fraction.__mul__(2, 6))
File "app.py", line 27, in __mul__
den = self.den * other.num
AttributeError: 'int' object has no attribute 'den'
解决方案
尝试这个
f1 = Fraction(1, 2)
f2 = Fraction(2, 3)
print(f1 * f2)
我在这里
- 创建一个
f1
类对象Fraction
是1/2
- 同样
f2
是2/3
- 现在
f1 * f2
自动调用with的dunder 方法__mul__
作为参数f1
f2
other
- 所以你应该看到预期的
Fraction
对象被打印出来
PS:你得到的原因AttributeError
是因为,__mul__
期望Fraction
对象被传递 - 当你传递int
s
推荐阅读
- javascript - 在找出主要因素时将结果设为未定义
- amazon-web-services - 如何确保 Athena 生成具有 bucket-owner-full-control 的 S3 对象
- mongodb - 模型上的猫鼬 findOneAndUpdate
- leveldb - 列族级别的“allow_concurrent_memtable_write”
- xamarin - 如何用背景图像填充 CCLayer?
- go - 使用 golang 仅检索具有 google-cloud 数据存储中的键的特定属性
- android - 如何使用意图在android中创建共享按钮?
- javascript - Chrome 同步处理 iframe 加载,而 Firefox 异步处理
- python - 如何识别 Google 表格中的第一个空列以使用 Python 附加数据框?
- c# - 在 Sql Kata 中获取原始 sql 字符串