如何添加不同类的两个变量?

2024-10-02 08:24:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在创建一个名为“分数”的类,需要定义一个将整数添加到这些分数的函数。我编写的代码给出了错误:

回溯(最近一次呼叫最后一次):

文件“”,第1行,在 布雷克(1,3)+1

TypeError:不支持+:“Breuk”和“int”的操作数类型

import math

class Breuk:
    def __init__(self, teller=1, noemer=1):
        self.teller = int(teller)
        self.noemer = int(noemer)
        while math.gcd(self.teller, self.noemer) != int(1):
            factor = math.gcd(self.teller, self.noemer)
            self.teller = int(self.teller / factor)
            self.noemer = int(self.noemer / factor)

    def __str__(self):
        return str(self.teller) + '/' + str(self.noemer)
    
    def __add__(self,other):
        if type(other) == int:
            other = Breuk(other, 1)
        elif type(self) == int:
            self.teller = self
            self.noemer = 1
        r = Breuk()
        r.teller = self.noemer*other.teller + self.teller*other.noemer
        r.noemer = self.noemer*other.noemer
        
        while math.gcd(r.teller, r.noemer) != 1:
            factor = int(math.gcd(r.teller, r.noemer))
            r.teller = int(r.teller / factor)
            r.noemer = int(r.noemer / factor)
        return r

Tags: selfreturndeftypemath分数intother
2条回答

它对我有效,但如果对你无效,请尝试以下方法:

if isinstance(other, int):
    other = Breuk(other, 1)

我在测试代码时没有遇到这个问题,所以我认为没有什么问题,但你是对的。 事实证明,您只需要添加以下代码:

def __radd__(self,other):
    if isinstance(other, int):
        other = Breuk(other, 1)
    elif type(self) == int:
        self.teller = self
        self.noemer = 1
    r = Breuk()
    r.teller = self.noemer*other.teller + self.teller*other.noemer
    r.noemer = self.noemer*other.noemer
    
    while math.gcd(r.teller, r.noemer) != 1:
        factor = int(math.gcd(r.teller, r.noemer))
        r.teller = int(r.teller / factor)
        r.noemer = int(r.noemer / factor)
    return r

调用5。add(Beurk(5,3))将失败,然后调用Beurk(5,3)。radd(5)将正常工作

相关问题 更多 >

    热门问题