[英]Python create built-in method for class
I made a class that can do some fraction arithmetic. 我做了一个可以做分数运算的类。 I change the built-in method of
__add__
, __sub__
, __mul__
,and __div__
so that it can do arithmetic with fractions. 我更改了
__add__
, __sub__
, __mul__
和__div__
的内置方法,以便可以对分数进行算术运算。 I can use it with the +
, -
, *
, /
symbols. 我可以将其与
+
, -
, *
, /
符号一起使用。 My question is, what do I have to do to be able to use __iadd__
as +=
. 我的问题是,我必须怎么做才能将
__iadd__
用作+=
。
class Fraction:
def __init__(self,num,den):
self.num = num
self.den = den
def __str__(self):
return str(self.num)+" / "+str(self.den)
def __add__(self,other):
num = self.num * other.den + other.num * self.den
den = self.den * other.den
common = self.gcf(num,den)
return Fraction(num/common , den/common)
def __iadd__(self,other):
self.num = self.num * other.den + other.num * self.den
self.den = self.den * other.den
common = self.gcf(self.num,self.den)
self.num = self.num/common
self.den = self.den/common
You are missing return self
at the end of your __iadd__
implementation. 在
__iadd__
实现的末尾,您缺少return self
。 Augmented assignment methods are allowed to return different instances, which is why return self
is necessary. 增强的赋值方法允许返回不同的实例,这就是为什么必须要
return self
原因。
In an unrelated note, you can reduce some code duplication by implementing addition in terms of in-place addition, like this: 在不相关的说明中,您可以通过就地加法实现加法来减少一些代码重复,如下所示:
def __add__(self, other):
clone = Fraction(self.num, self.den)
clone += other
return clone
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.