【问题标题】:Calling Private Methods Recursively递归调用私有方法
【发布时间】:2021-11-07 15:57:19
【问题描述】:

我正在编写一个代码,它有一个带有属性 Numerator 和 Denominator 的 Fraction 类。输出应以简化形式显示分数。例如20/100 应显示为 1/5。 我尝试了下面的代码,但得到如下类型错误:

TypeError: unsupported operand type(s) for /: 'int' and 'NoneType'

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:
            self.__GCD(b,a%b)
f=fraction()
f.get_data()
f.display_data()

我不知道如何解决这个错误。请帮助我,因为我是 Python 新手,想要建立强大的基础。

【问题讨论】:

    标签: function oop recursion private self


    【解决方案1】:

    问题出在这个函数定义中:

    def __GCD(self,a,b):
        if (b==0):
            return a
        else:
            self.__GCD(b,a%b)
    

    else 子句中没有 return 语句。 (另外,else 子句可以是 implicit 而不是 explicit。)改为尝试:

    def __GCD(self, a, b):
        if b == 0:
            return a
        
        return self.__GCD(b, a % b)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 2014-03-02
      • 2016-03-02
      • 1970-01-01
      • 2018-05-03
      • 2014-07-07
      • 1970-01-01
      相关资源
      最近更新 更多