如何对Python中的class进行一元运算?

How to perform unary operations on a class in Python?

我写了一段代码,其中定义了一个 class Fraction。在整个代码中,可以执行所有二进制操作,例如 +, -, /, * 。现在我还希望能够对 class Fraction 执行一元运算,例如 abs() 等。但是,这目前不起作用,例如在执行一元运算时abs() 我得到一个 TypeError:abs () 的错误操作数类型:'Fraction'。下面是纯分数减法的部分代码,代表整个代码:

def gcd(denominator, numerator):
    if numerator == 0:
        return denominator
    else:
        return gcd(numerator, (denominator % numerator))

class Fraction:
    
    def __init__(self,numerator = 0, denominator = 1):

        self.numerator = int(numerator / gcd(abs(denominator),abs(numerator) ))
        self.denominator = int(denominator / gcd(abs(denominator),abs(numerator) ))
        if self.denominator < 0:
            self.denominator = abs(self.denominator)
            self.numerator = -1*self.numerator
        elif self.denominator == 0:
            raise ZeroDivisionError
        
    def __str__(self):
        if self.denominator == 1:
            return str(self.numerator)
        else:
            return str(self.numerator) + "/" + str(self.denominator)
    
    def __neg__(self):
        return Fraction(-self.numerator, self.denominator)
    
    def __rsub__(self,other):
        return self.__sub__(other)

    def __sub__(self,other):
        if type(other) == int:
            other = Fraction(other,1)
            return self.sub(other)
        else:
            
            return self.sub(other)
    
    def sub(self,other):
        result = Fraction()
        
        result.numerator = other.denominator * self.numerator - self.denominator * other.numerator
        result.denominator = other.denominator * self.denominator
        
        multiple = gcd(result.denominator,result.numerator)
        
        result.numerator = int(result.numerator / multiple)
        result.denominator = int(result.denominator / multiple)
        
        if result.denominator < 0:
            result.denominator = abs(result.denominator)
            result.numerator = 0 - result.numerator
            return result    
        
        else:
            return result
        
        return result


p = Fraction(2,3)
q = Fraction(4,5)

r = (p - q)

我想要的是,当我给出语句 print(abs(r)) 时,输出是绝对值的分数。因此,在 p = Fraction(2,3)q = Fraction(4,5)r = 的示例中(p - q)。然后语句 print(r) 给出输出 -2/15,语句 print(abs(r)) 给出输出 2/15。或者,例如 print(float(r)) 给出输出 -0.133333333。但是,我不断收到前面提到的 TypeError.

我已经找了一段时间了,但到目前为止我还没有找到解决办法,你知道我该如何解决这个问题吗?

提前致谢!

评论里已经提到实现__abs____float__.

将此添加到您的 class:

    def __abs__(self):
        return Fraction(abs(self.numerator), abs(self.denominator))

    def __float__(self):
        return self.numerator / self.denominator

可能

    def __abs__(self):
        return Fraction(abs(self.numerator), self.denominator)

已经足够了,因为你的分母总是正数。

>>> p = Fraction(2, 3)
>>> q = Fraction(4, 5)
>>> r = p - q
>>> print(r)
-2/15
>>> print(abs(r))
2/15
>>> print(float(r))
-0.13333333333333333