如何在返回语句中调用另一个局部函数的局部函数?

1 投票
2 回答
970 浏览
提问于 2025-04-17 20:25

当我运行Fraction类的时候,出现了“全局名称simplify未定义”的错误。虽然我在同一个Fraction类里定义了simplify函数。这个simplify函数单独运行时没有问题。但是当Fraction类在没有simplify函数的情况下运行时,返回的结果没有被简化,这让我很困惑。为什么在我尝试对Fraction进行简化后会出现这个问题呢?

class Fraction:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    #simplify, simplifies the fraction.(2/4 to 1/2)
    #add, adds two fractions and then returns the simplified fraction.
    def __add__ (self, f):
        if (self.b == f.b) :
            return simplify(Fraction(self.a + f.a , f.b))
        else :
            pro = self.b * f.b
            return simplify(Fraction(self.a * f.b + f.a * self.b , pro))

2 个回答

1

因为 simplify 是一个局部函数,所以你应该用 Class.function 这样的写法来调用它。要是你直接运行 simplify,解释器会去找一个全局的 simplify 函数。

你可以试试下面这个方法:

class Fraction:
    def __init__(self, a, b):
        self.a = a
        self.b = b

#simplify, simplifies the fraction.(2/4 to 1/2)
#add, adds two fractions and then returns the simplified fraction.
    def __add__ (self, f):
        if (self.b == f.b) :
            return Fraction.simplify(Fraction(self.a + f.a , f.b))
        else :
            pro = self.b * f.b
            return Fraction.simplify(Fraction(self.a * f.b + f.a * self.b , pro))

希望这能帮到你。

0

你把函数和方法搞混了。

函数的写法像这样 f(a, b)。而方法的写法则是 <类实例>.method(a, b)

看看这个例子(我用了Python的fractions模块来简单演示“简化”):

import fractions

class MyFraction:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def simplify(self):
        rtr=fractions.Fraction(self.a, self.b)
        print('"simplify({}, {})"={}'.format(self.a,self.b, rtr))    
        return rtr

    #simplify, simplifies the fraction.(2/4 to 1/2)
    #add, adds two fractions and then returns the simplified fraction.
    def __repr__(self):
        return '{}/{}'.format(self.a, self.b)

    # alternatively, if you want to always print a simplified fraction:
    # def __str__(self):
        # return fractions.Fraction(self.a, self.b).__str__()

    def __add__ (self, f):
        if (self.b == f.b) :
            return MyFraction(self.a + f.a , f.b).simplify()
        else :
            pro = self.b * f.b
            return MyFraction(self.a * f.b + f.a * self.b , pro).simplify()

print(MyFraction(2,4))   
# 2/4
print(MyFraction(1, 2)+MyFraction(20, 30))  
# "simplify(70, 60)"=7/6
# 7/6

从风格上讲,你可以在你的类里用“numerator”代替“a”,用“denominator”代替“b”。你也可以把它命名为“MyFraction”,而不是库里的“Fraction”,这样别人看你的代码时就不会混淆了。

撰写回答