gpt4 book ai didi

python - 如何在 return 语句中调用另一个本地函数内的本地函数?

转载 作者:太空宇宙 更新时间:2023-11-03 18:32:55 27 4
gpt4 key购买 nike

当我运行 Fraction 类时,出现全局名称简化未定义的错误。虽然我在同一个类 Fraction 中定义了简化函数。独立运行时的简化功能运行完美。 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))

最佳答案

由于 simplify 是本地函数,因此您应该使用语法 Class.function。尝试运行简化,解释器将寻找全局 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))

希望有帮助

关于python - 如何在 return 语句中调用另一个本地函数内的本地函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22114229/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com