You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python递归调用类私有方法实现分数化简报TypeError如何解决?

错误根源定位
  • 核心错误出现在__GCD方法的递归分支:当参数b≠0时,仅调用了递归方法,没有添加return语句返回计算结果,Python函数无显式返回时默认返回None,这就导致common_divisor被赋值为None,执行self.__num / common_divisor时触发了int和NoneType不支持除法运算的报错。
  • 额外优化点:Python3中/运算符会返回浮点数,最终会输出1.0 / 5.0这类不符合分数展示规范的结果,建议替换为//整数除法运算符,保持分子分母为整数类型。
修复后完整代码
class fraction:
    def get_data(self):
        self.__num=int(input("Enter the Nr:"))
        self.__deno=int(input("Enter the Dr:"))
        if (self.__deno==0):
            print("Fraction not possible")
            exit()
    def display_data(self):
        self.__simplify()
        print(self.__num,"/",self.__deno)
    def __simplify(self):
        print("The simplified fraction is")
        common_divisor=self.__GCD(self.__num,self.__deno)
        self.__num = self.__num // common_divisor
        self.__deno = self.__deno // common_divisor
    def __GCD(self,a,b):
        if (b==0):
            return a
        else:
            # 补充return语句返回递归结果
            return self.__GCD(b,a%b)
f=fraction()
f.get_data()
f.display_data()
运行效果验证

输入分子20、分母100时,程序输出如下:

The simplified fraction is
1 / 5

内容的提问来源于stack exchange,提问作者Python Learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 08:00:01